<?php
require_once '../includes/config.php';
require_once __DIR__ . '/includes/admin_auth.php';
require_once __DIR__ . '/includes/admin_header.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error'] = "Invalid request method";
    header("Location: profile.php");
    exit();
}

// Get form data
$email = trim($_POST['email']);
$fullName = trim($_POST['full_name']);

// Validate data
if (empty($email) || empty($fullName)) {
    $_SESSION['error'] = "All fields are required";
    header("Location: profile.php");
    exit();
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $_SESSION['error'] = "Invalid email format";
    header("Location: profile.php");
    exit();
}

try {
    $stmt = $db->prepare("UPDATE admin_users SET email = ?, full_name = ? WHERE id = ?");
    $stmt->bind_param("ssi", $email, $fullName, $_SESSION['admin_id']);

    if ($stmt->execute()) {
        // Update session data
        $_SESSION['admin_name'] = $fullName;
        $_SESSION['success'] = "Profile updated successfully";
    } else {
        throw new Exception("Failed to update profile: " . $stmt->error);
    }

    $stmt->close();

} catch (Exception $e) {
    $_SESSION['error'] = "Database error: " . $e->getMessage();
}

header("Location: profile.php");
exit();
?>
