<?php
// =====================================================
// transaction_pin.php – Compatible with PHP 5/6
// Includes transaction_pin_date field
// =====================================================

ob_start();
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

// JSON & CORS Headers
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

require("dbcon.php"); // must define $pdo (PDO connection)

// Read and decode input
$rawInput = trim(file_get_contents("php://input"));
$input = json_decode($rawInput, true);

// Log input
file_put_contents(__DIR__ . "/log.txt", date("Y-m-d H:i:s") . " " . $rawInput . PHP_EOL, FILE_APPEND);

// Helper to respond with JSON
function respond($data) {
    if (ob_get_length()) {
        @ob_clean();
    }
    echo json_encode($data);
    exit;
}

// Validate JSON
if (json_last_error() !== JSON_ERROR_NONE) {
    respond(array("success" => false, "message" => "Invalid JSON input"));
}

if (!$input || !isset($input['action'])) {
    respond(array("success" => false, "message" => "Invalid request", "debug" => $rawInput));
}

$action = $input['action'];

// =====================================================
// 1. CHECK IF USER HAS A TRANSACTION PIN
// =====================================================
if ($action === "check_transaction_pin") {
    $userId = isset($input['userId']) ? intval($input['userId']) : 0;

    if ($userId <= 0) {
        respond(array("success" => false, "message" => "Invalid user ID"));
    }

    $stmt = $pdo->query("SELECT transaction_pin FROM users WHERE id = $userId");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $hasPin = !empty($row['transaction_pin']);
        respond(array(
            "success" => true,
            "hasPin"  => $hasPin,
            "message" => $hasPin ? "User has a PIN" : "No PIN found"
        ));
    } else {
        respond(array("success" => false, "message" => "User not found"));
    }
}

// =====================================================
// 2. CREATE NEW TRANSACTION PIN
// =====================================================
if ($action === "create_transaction_pin") {
    $userId = isset($input['userId']) ? intval($input['userId']) : 0;
    $newPin = isset($input['newPin']) ? trim($input['newPin']) : '';

    if ($userId <= 0) {
        respond(array("success" => false, "message" => "Invalid user ID"));
    }

    if (strlen($newPin) !== 4 || !ctype_digit($newPin)) {
        respond(array("success" => false, "message" => "PIN must be exactly 4 digits"));
    }

    // Check if user already has a PIN
    $check = $pdo->query("SELECT transaction_pin FROM users WHERE id = $userId");
    $existing = $check->fetch(PDO::FETCH_ASSOC);
    $existingPin = isset($existing['transaction_pin']) ? $existing['transaction_pin'] : '';

    if (!empty($existingPin)) {
        respond(array("success" => false, "message" => "PIN already exists. Please change it instead."));
    }

    // Save new PIN and timestamp
    $pinDate = date("Y-m-d H:i:s");
    $update = $pdo->exec("UPDATE users SET transaction_pin = '$newPin', transaction_pin_date = '$pinDate' WHERE id = $userId");

    if ($update > 0) {
        respond(array("success" => true, "message" => "PIN created successfully", "pin_date" => $pinDate));
    } else {
        respond(array("success" => false, "message" => "Failed to create PIN"));
    }
}

// =====================================================
// 3. CHANGE EXISTING TRANSACTION PIN
// =====================================================
if ($action === "change_transaction_pin") {
    $userId     = isset($input['userId']) ? intval($input['userId']) : 0;
    $currentPin = isset($input['currentPin']) ? trim($input['currentPin']) : '';
    $newPin     = isset($input['newPin']) ? trim($input['newPin']) : '';

    if ($userId <= 0) {
        respond(array("success" => false, "message" => "Invalid user ID"));
    }

    $stmt = $pdo->query("SELECT transaction_pin FROM users WHERE id = $userId");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        respond(array("success" => false, "message" => "User not found"));
    }

    $storedPin = isset($row['transaction_pin']) ? $row['transaction_pin'] : '';

    if ($storedPin !== $currentPin) {
        respond(array("success" => false, "message" => "Current PIN is incorrect"));
    }

    if (strlen($newPin) !== 4 || !ctype_digit($newPin)) {
        respond(array("success" => false, "message" => "New PIN must be 4 digits"));
    }

    $updateDate = date("Y-m-d H:i:s");
    $update = $pdo->exec("UPDATE users SET transaction_pin = '$newPin', transaction_pin_date = '$updateDate' WHERE id = $userId");

    if ($update > 0) {
        respond(array("success" => true, "message" => "PIN changed successfully", "pin_date" => $updateDate));
    } else {
        respond(array("success" => false, "message" => "Failed to change PIN"));
    }
}

// =====================================================
// DEFAULT RESPONSE
// =====================================================
respond(array("success" => false, "message" => "Invalid action"));
?>
