<?php
require_once 'includes/config.php';
requireLogin();
$user = getCurrentUser();
$db   = getDB();

// Create pin table
try {
    $db->exec("CREATE TABLE IF NOT EXISTS user_pins (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL UNIQUE,
        pin_hash VARCHAR(255) NOT NULL,
        is_enabled TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch(Exception $e){}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    header('Content-Type: application/json');

    if ($action === 'verify') {
        $pin = sanitize($_POST['pin'] ?? '');
        $attempts = $_SESSION['pin_attempts'] ?? 0;
        if ($attempts >= 3) {
            session_destroy();
            echo json_encode(['ok'=>false,'logout'=>true,'message'=>'Too many attempts. Logged out.']);
            exit;
        }
        $row = $db->prepare("SELECT pin_hash FROM user_pins WHERE user_id=? AND is_enabled=1");
        $row->execute([$user['id']]); $row = $row->fetch();
        if ($row && password_verify($pin, $row['pin_hash'])) {
            $_SESSION['pin_verified']  = true;
            $_SESSION['pin_last_time'] = time();
            $_SESSION['pin_attempts']  = 0;
            echo json_encode(['ok'=>true]);
        } else {
            $_SESSION['pin_attempts'] = $attempts + 1;
            $left = 3 - ($_SESSION['pin_attempts']);
            echo json_encode(['ok'=>false,'message'=>'Wrong PIN. '.$left.' attempts left.','attempts'=>$_SESSION['pin_attempts']]);
        }
        exit;
    }

    if ($action === 'lock') {
        // Reset PIN verified state — next page load will require PIN
        $_SESSION['pin_verified']  = false;
        $_SESSION['pin_last_time'] = 0;
        echo json_encode(['ok'=>true]);
        exit;
    }

    if ($action === 'set') {
        $pin     = sanitize($_POST['pin']     ?? '');
        $confirm = sanitize($_POST['confirm'] ?? '');
        if (strlen($pin) !== 4 || !ctype_digit($pin)) { echo json_encode(['ok'=>false,'message'=>'PIN must be 4 digits']); exit; }
        if ($pin !== $confirm) { echo json_encode(['ok'=>false,'message'=>'PINs do not match']); exit; }
        $hash = password_hash($pin, PASSWORD_DEFAULT);
        $db->prepare("INSERT INTO user_pins (user_id,pin_hash) VALUES (?,?) ON DUPLICATE KEY UPDATE pin_hash=?,is_enabled=1,updated_at=NOW()")
           ->execute([$user['id'],$hash,$hash]);
        $_SESSION['pin_verified']  = true;
        $_SESSION['pin_last_time'] = time();
        echo json_encode(['ok'=>true,'message'=>'PIN set successfully!']);
        exit;
    }

    if ($action === 'disable') {
        $db->prepare("UPDATE user_pins SET is_enabled=0 WHERE user_id=?")->execute([$user['id']]);
        $_SESSION['pin_verified'] = true;
        echo json_encode(['ok'=>true]);
        exit;
    }

    if ($action === 'change') {
        $old  = sanitize($_POST['old']  ?? '');
        $new  = sanitize($_POST['new']  ?? '');
        $conf = sanitize($_POST['confirm'] ?? '');
        $row  = $db->prepare("SELECT pin_hash FROM user_pins WHERE user_id=? AND is_enabled=1");
        $row->execute([$user['id']]); $row = $row->fetch();
        if (!$row || !password_verify($old, $row['pin_hash'])) { echo json_encode(['ok'=>false,'message'=>'Current PIN incorrect']); exit; }
        if (strlen($new) !== 4 || !ctype_digit($new)) { echo json_encode(['ok'=>false,'message'=>'New PIN must be 4 digits']); exit; }
        if ($new !== $conf) { echo json_encode(['ok'=>false,'message'=>'PINs do not match']); exit; }
        $db->prepare("UPDATE user_pins SET pin_hash=? WHERE user_id=?")->execute([password_hash($new,PASSWORD_DEFAULT),$user['id']]);
        echo json_encode(['ok'=>true,'message'=>'PIN changed!']);
        exit;
    }
}

// Check PIN status
$pinRow = $db->prepare("SELECT * FROM user_pins WHERE user_id=? AND is_enabled=1");
$pinRow->execute([$user['id']]); $pinRow = $pinRow->fetch();
$hasPin = !!$pinRow;

echo json_encode(['has_pin'=>$hasPin]);
