<?php
require_once '../config.php';

// Ensure session is started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: ' . BASE_URL . '/admin/login');
    exit;
}

$admin_id = $_SESSION['admin_id'];
$message = '';
$message_type = '';

$conn = get_db_connection();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($full_name) || empty($email)) {
        $message = 'Full name and email are required.';
        $message_type = 'danger';
    } else {
        // Update name and email
        $stmt = $conn->prepare("UPDATE admin_users SET full_name = ?, email = ? WHERE id = ?");
        $stmt->bind_param("ssi", $full_name, $email, $admin_id);

        if ($stmt->execute()) {
            $_SESSION['admin_name'] = $full_name;
            $_SESSION['admin_email'] = $email;
            $message = 'Profile updated successfully.';
            $message_type = 'success';

            // Handle password change if provided
            if (!empty($new_password)) {
                if ($new_password !== $confirm_password) {
                    $message = 'Passwords do not match.';
                    $message_type = 'danger';
                } elseif (strlen($new_password) < 6) {
                    $message = 'Password must be at least 6 characters long.';
                    $message_type = 'danger';
                } else {
                    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt_pw = $conn->prepare("UPDATE admin_users SET password = ? WHERE id = ?");
                    $stmt_pw->bind_param("si", $hashed_password, $admin_id);
                    if ($stmt_pw->execute()) {
                        $message = 'Profile and password updated successfully.';
                        $message_type = 'success';
                    } else {
                        $message = 'Error updating password.';
                        $message_type = 'danger';
                    }
                    $stmt_pw->close();
                }
            }
        } else {
            $message = 'Error updating profile.';
            $message_type = 'danger';
        }
        $stmt->close();
    }
}

// Get current user data
$stmt = $conn->prepare("SELECT username, email, full_name FROM admin_users WHERE id = ?");
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

$page_title = 'My Profile';
require_once 'includes/admin-header.php';
?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="card" style="max-width: 900px; margin: 0 auto;">
    <div class="card-header">
        <h2 class="card-title">Edit Profile</h2>
    </div>

    <form method="POST" action="" class="profile-form">
        <div class="form-row" style="margin-bottom: 24px;">
            <div class="form-group">
                <label>Username</label>
                <div style="position: relative;">
                    <i class="fas fa-user-lock"
                        style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--text-muted);"></i>
                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['username']); ?>"
                        disabled
                        style="padding-left: 44px; background-color: var(--light); cursor: not-allowed; opacity: 0.7;">
                </div>
                <small style="color: var(--text-muted); font-size: 12px; margin-top: 4px; display: block;">Username
                    cannot be changed for security reasons.</small>
            </div>
            <div class="form-group">
                <label for="email">Email Address</label>
                <div style="position: relative;">
                    <i class="fas fa-envelope"
                        style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--secondary);"></i>
                    <input type="email" id="email" name="email" class="form-control" style="padding-left: 44px;"
                        value="<?php echo htmlspecialchars($user['email']); ?>" required>
                </div>
            </div>
        </div>

        <div class="form-group" style="margin-bottom: 32px;">
            <label for="full_name">Full Name</label>
            <div style="position: relative;">
                <i class="fas fa-id-card"
                    style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--secondary);"></i>
                <input type="text" id="full_name" name="full_name" class="form-control" style="padding-left: 44px;"
                    value="<?php echo htmlspecialchars($user['full_name']); ?>" required>
            </div>
        </div>

        <div
            style="background: var(--light); padding: 24px; border-radius: var(--radius-md); border: 1px solid var(--border); margin-bottom: 32px;">
            <h3
                style="font-size: 16px; font-weight: 700; margin-bottom: 16px; display: flex; align-items: center; gap: 8px;">
                <i class="fas fa-key" style="color: var(--warning);"></i> Change Password
            </h3>
            <p style="color: var(--text-muted); font-size: 13px; margin-bottom: 20px;">Leave these fields blank if you
                don't want to change your password.</p>

            <div class="form-row">
                <div class="form-group" style="margin-bottom: 0;">
                    <label for="new_password">New Password</label>
                    <div style="position: relative;">
                        <i class="fas fa-lock"
                            style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--secondary);"></i>
                        <input type="password" id="new_password" name="new_password" class="form-control"
                            style="padding-left: 44px;" placeholder="Enter new password">
                    </div>
                </div>
                <div class="form-group" style="margin-bottom: 0;">
                    <label for="confirm_password">Confirm New Password</label>
                    <div style="position: relative;">
                        <i class="fas fa-shield-alt"
                            style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: var(--secondary);"></i>
                        <input type="password" id="confirm_password" name="confirm_password" class="form-control"
                            style="padding-left: 44px;" placeholder="Confirm new password">
                    </div>
                </div>
            </div>
        </div>

        <div style="display: flex; gap: 16px; justify-content: flex-end;">
            <a href="/admin/dashboard" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i> Update Profile
            </button>
        </div>
    </form>
</div>

<style>
    /* Use existing admin variables for consistency */
    .profile-form .form-group label {
        margin-bottom: 8px;
        font-weight: 600;
        color: var(--dark);
    }

    .profile-form .form-control {
        border: 1px solid var(--border);
        transition: var(--transition);
    }

    .profile-form .form-control:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 4px var(--primary-light);
    }

    .alert {
        padding: 16px;
        border-radius: 8px;
        margin-bottom: 24px;
        display: flex;
        align-items: center;
        gap: 12px;
        max-width: 800px;
        margin-left: auto;
        margin-right: auto;
    }

    .alert-success {
        background-color: #ecfdf5;
        color: #065f46;
        border: 1px solid #a7f3d0;
    }

    .alert-danger {
        background-color: #fef2f2;
        color: #991b1b;
        border: 1px solid #fecaca;
    }

    .btn {
        padding: 12px 24px;
        border-radius: var(--radius-md);
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: var(--transition);
    }

    .btn-primary {
        background: var(--primary);
        color: var(--white);
    }

    .btn-primary:hover {
        background: var(--primary-dark);
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
    }

    .btn-secondary {
        background: var(--white);
        color: var(--text-main);
        border: 1px solid var(--border);
    }

    .btn-secondary:hover {
        background: var(--light);
    }
</style>

<?php require_once 'includes/admin-footer.php'; ?>