<?php
require_once __DIR__ . '/../app/init.php';
app_require_login();

$companyId = app_context_company_id();
$companies = app_current_user_company_options();
if (($companyId === null || $companyId <= 0) && !empty($companies[0]['id'])) {
    $companyId = (int) $companies[0]['id'];
}
if ($companyId !== null && $companyId > 0) {
    app_set_context_company_id((int) $companyId);
}
$company = $companyId ? app_company_by_id((int) $companyId) : null;
$error = null;
$success = app_flash('success');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        app_verify_csrf();
        $currentPassword = (string) ($_POST['current_password'] ?? '');
        $newPassword = (string) ($_POST['new_password'] ?? '');
        $confirmPassword = (string) ($_POST['confirm_password'] ?? '');

        if ($currentPassword === '' || $newPassword === '' || $confirmPassword === '') {
            throw new RuntimeException('Please fill all password fields.');
        }
        if ($newPassword !== $confirmPassword) {
            throw new RuntimeException('New password confirmation does not match.');
        }
        if (strlen($newPassword) < 6) {
            throw new RuntimeException('New password must be at least 6 characters.');
        }

        $userId = (int) (app_current_user()['id'] ?? 0);
        $stmt = app_pdo()->prepare('SELECT password_hash FROM users WHERE id = :id AND is_active = 1 LIMIT 1');
        $stmt->execute(['id' => $userId]);
        $hash = (string) ($stmt->fetchColumn() ?: '');
        if ($hash === '' || !password_verify($currentPassword, $hash)) {
            throw new RuntimeException('Current password is incorrect.');
        }

        $update = app_pdo()->prepare('UPDATE users SET password_hash = :password_hash WHERE id = :id');
        $update->execute([
            'password_hash' => password_hash($newPassword, PASSWORD_DEFAULT),
            'id' => $userId,
        ]);

        app_flash('success', 'Password changed successfully.');
        app_redirect('change_password.php');
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}
?>
<!doctype html>
<html <?= app_html_attrs() ?>>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= app_escape(app_t((string) app_config('app_name'))) ?> - <?= app_escape(app_t('Change Password')) ?></title>
  <link rel="icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="shortcut icon" href="assets/favicon.svg" type="image/svg+xml">
  <link rel="stylesheet" href="assets/styles.css">
</head>
<body>
<div class="app-shell has-sidebar">
  <?= app_sidebar_nav_html('change_password', null, $companyId) ?>

  <header class="header">
    <div class="header-side right">
      <div class="header-title"><?= app_escape(app_t('Change Password')) ?></div>
      <div class="header-subtitle"><?= app_escape(app_t('Keep your account access secure.')) ?></div>
    </div>
    <div class="header-center">
      <img src="<?= app_escape(app_logo_path_for_header($company)) ?>" alt="Logo" class="school-logo">
    </div>
    <div class="header-side left">
      <div class="header-title"><?= app_escape((string) (app_current_user()['full_name'] ?? app_current_username())) ?></div>
      <div class="header-subtitle"><?= app_escape((string) ($company['name'] ?? 'N/A')) ?></div>
    </div>
  </header>

  <main class="dashboard-content">
    <section class="panel-card">
      <div class="section-heading">
        <h3><?= app_escape(app_t('Change Password')) ?></h3>
        <span><?= app_escape(app_t('Update the password for your current user only.')) ?></span>
      </div>

      <?php if ($success !== null): ?>
        <div class="alert success"><?= app_escape($success) ?></div>
      <?php endif; ?>
      <?php if ($error !== null): ?>
        <div class="alert error"><?= app_escape($error) ?></div>
      <?php endif; ?>

      <form method="post" class="form-grid two">
        <?= app_csrf_field() ?>
        <div class="field">
          <label for="current_password"><?= app_escape(app_t('Current Password')) ?></label>
          <div class="password-control">
            <input id="current_password" name="current_password" type="password" autocomplete="current-password" required>
            <button class="password-toggle" type="button" data-toggle-password data-target="current_password">Show</button>
          </div>
        </div>
        <div class="field">
          <label for="new_password"><?= app_escape(app_t('New Password')) ?></label>
          <div class="password-control">
            <input id="new_password" name="new_password" type="password" autocomplete="new-password" required>
            <button class="password-toggle" type="button" data-toggle-password data-target="new_password">Show</button>
          </div>
        </div>
        <div class="field">
          <label for="confirm_password"><?= app_escape(app_t('Confirm Password')) ?></label>
          <div class="password-control">
            <input id="confirm_password" name="confirm_password" type="password" autocomplete="new-password" required>
            <button class="password-toggle" type="button" data-toggle-password data-target="confirm_password">Show</button>
          </div>
        </div>
        <div class="form-actions">
          <button class="btn btn-primary" type="submit"><?= app_escape(app_t('Save Password')) ?></button>
          <a class="btn btn-secondary" href="index.php<?= $companyId ? '?company_id=' . (int) $companyId : '' ?>"><?= app_escape(app_t('Dashboard')) ?></a>
        </div>
      </form>
    </section>
  </main>
</div>
<?= app_back_button_html() ?>
<script src="assets/app.js"></script>
</body>
</html>
