<?php
require_once __DIR__ . '/../config/master_database.php';
session_start();
if (empty($_SESSION['super_admin_id'])) { header('Location: login.php'); exit; }

$myId = (int) $_SESSION['super_admin_id'];
$stmt = $pdoMaster->prepare("SELECT * FROM super_admins WHERE id = ?");
$stmt->execute([$myId]);
$me = $stmt->fetch();
if (!$me) { header('Location: logout.php'); exit; }

$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $currentPassword = $_POST['current_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $newPasswordConfirm = $_POST['new_password_confirm'] ?? '';

    if (!$name) $errors[] = 'Name is required.';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';
    if (!password_verify($currentPassword, $me['password'])) $errors[] = 'Current password is incorrect.';

    if ($email !== $me['email']) {
        $chk = $pdoMaster->prepare("SELECT id FROM super_admins WHERE email = ? AND id != ?");
        $chk->execute([$email, $myId]);
        if ($chk->fetch()) $errors[] = 'That email is already used by another super admin account.';
    }

    if ($newPassword !== '' || $newPasswordConfirm !== '') {
        if (strlen($newPassword) < 6) $errors[] = 'New password must be at least 6 characters.';
        if ($newPassword !== $newPasswordConfirm) $errors[] = 'New password and confirmation do not match.';
    }

    if (empty($errors)) {
        if ($newPassword !== '') {
            $pdoMaster->prepare("UPDATE super_admins SET name = ?, email = ?, password = ? WHERE id = ?")
                ->execute([$name, $email, password_hash($newPassword, PASSWORD_DEFAULT), $myId]);
        } else {
            $pdoMaster->prepare("UPDATE super_admins SET name = ?, email = ? WHERE id = ?")
                ->execute([$name, $email, $myId]);
        }
        $success = 'Account updated successfully.';
        $me['name'] = $name;
        $me['email'] = $email;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Account - Super Admin</title>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/style.css?v=5">
</head>
<body style="padding:40px;max-width:600px;margin:0 auto;">
    <h2 style="font-family:var(--font-display);">My Account</h2>
    <p><a href="dashboard.php">&larr; Back to companies list</a></p>

    <?php foreach ($errors as $e): ?><div class="alert alert-danger"><?= htmlspecialchars($e) ?></div><?php endforeach; ?>
    <?php if ($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>

    <form method="POST">
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" required value="<?= htmlspecialchars($me['name']) ?>">
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="email" name="email" required value="<?= htmlspecialchars($me['email']) ?>">
        </div>
        <hr>
        <div class="form-group">
            <label>Current Password <span class="text-faint">(required to save any change)</span></label>
            <input type="password" name="current_password" required>
        </div>
        <div class="form-group">
            <label>New Password <span class="text-faint">(leave blank to keep current password)</span></label>
            <input type="password" name="new_password">
        </div>
        <div class="form-group">
            <label>Confirm New Password</label>
            <input type="password" name="new_password_confirm">
        </div>
        <button type="submit" class="btn btn-primary">Save Changes</button>
    </form>
</body>
</html>