<?php
session_start();
require_once '../config/db.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$adminId = $_SESSION['admin_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $firstName = capitalizeWords(trim($_POST['first_name'] ?? ''));
    $lastName = capitalizeWords(trim($_POST['last_name'] ?? ''));
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone_number'] ?? '');
    $username = trim($_POST['username'] ?? '');

    if (empty($firstName) || empty($lastName) || empty($username)) {
        echo json_encode(['success' => false, 'message' => 'Please fill in all required fields.']);
        exit;
    }

    try {
        // Check if username is taken by another admin
        $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM admins WHERE username = ? AND id != ?");
        $stmtCheck->execute([$username, $adminId]);
        if ($stmtCheck->fetchColumn() > 0) {
            echo json_encode(['success' => false, 'message' => 'Username is already taken.']);
            exit;
        }

        $stmt = $pdo->prepare("UPDATE admins SET first_name = ?, last_name = ?, phone_number = ?, username = ? WHERE id = ?");
        if ($stmt->execute([$firstName, $lastName, $phone, $username, $adminId])) {
            $_SESSION['admin_user'] = $username;
            echo json_encode(['success' => true, 'message' => 'Profile updated successfully!', 'new_username' => $username]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update profile.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>