<?php
// ProfileController
requireLogin();
$db  = Database::getInstance();
$uid = (int)$_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $name  = sanitize($_POST['officer_name'] ?? '');
    $phone = sanitize($_POST['phone_number'] ?? '');
    $params = [$name, $phone];
    $sql    = 'UPDATE users SET officer_name=?, phone_number=?';

    if (!empty($_POST['password']) && !empty($_POST['password_confirm'])) {
        if ($_POST['password'] !== $_POST['password_confirm']) {
            setFlash('error', 'Passwords do not match.');
            header('Location: ' . APP_URL . '/index.php?page=profile'); exit;
        }
        $sql .= ', password=?';
        $params[] = password_hash($_POST['password'], PASSWORD_BCRYPT, ['cost' => 12]);
    }

    // Signature upload
    if (!empty($_FILES['signature']['name'])) {
        $ext = strtolower(pathinfo($_FILES['signature']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['png', 'jpg', 'jpeg'])) {
            $filename = 'sig_' . $uid . '_' . time() . '.' . $ext;
            move_uploaded_file($_FILES['signature']['tmp_name'], SIGNATURE_PATH . $filename);
            $sql .= ', signature=?';
            $params[] = $filename;
        }
    }

    $sql .= ' WHERE user_id=?';
    $params[] = $uid;
    $db->prepare($sql)->execute($params);
    $_SESSION['name'] = $name;
    logActivity('update_profile', 'profile', 'Profile updated');
    setFlash('success', 'Profile updated successfully.');
    header('Location: ' . APP_URL . '/index.php?page=profile'); exit;
}

$stmt = $db->prepare('SELECT * FROM users WHERE user_id = ?');
$stmt->execute([$uid]);
$profileUser = $stmt->fetch();
include __DIR__ . '/../views/shared/profile.php';
