<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$action = cleanInput($_POST['action'] ?? '');
$userid = currentUserId();

try {
    if ($action === 'updateprofile') {
        $name = cleanInput($_POST['name'] ?? '');
        $phone = cleanInput($_POST['phone'] ?? '');
        if ($name === '' || $phone === '') {
            jsonOut(false, 'Name and phone are required');
        }
        $stmt = $pdo->prepare("UPDATE adminuser SET name = ?, phone = ? WHERE id = ?");
        $stmt->execute([$name, $phone, $userid]);
        $_SESSION['name'] = $name;
        logActivity($pdo, 'adminuser', $userid, 'updateprofile', 'admin', $userid, 'Profile updated');
        jsonOut(true, 'Profile updated successfully');
    }

    if ($action === 'changepassword') {
        $currentpassword = cleanInput($_POST['currentpassword'] ?? '');
        $newpassword = cleanInput($_POST['newpassword'] ?? '');

        if ($currentpassword === '' || $newpassword === '') {
            jsonOut(false, 'Both current and new password are required');
        }
        if (strlen($newpassword) < 6) {
            jsonOut(false, 'New password must be at least 6 characters');
        }

        $stmt = $pdo->prepare("SELECT password FROM adminuser WHERE id = ?");
        $stmt->execute([$userid]);
        $row = $stmt->fetch();

        if (!$row || !verifyPassword($currentpassword, $row['password'])) {
            jsonOut(false, 'Current password is incorrect');
        }

        $upd = $pdo->prepare("UPDATE adminuser SET password = ? WHERE id = ?");
        $upd->execute([hashPassword($newpassword), $userid]);

        logActivity($pdo, 'adminuser', $userid, 'changepassword', 'admin', $userid, 'Password changed by self');

        jsonOut(true, 'Password changed successfully');
    }

    jsonOut(false, 'Invalid action');
} catch (Exception $e) {
    logDebug('[ajax_admin_profile] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
