<?php
// =====================================================
// transaction_pin.php – Compatible with PHP 5/6
// Includes transaction_pin_date field
// Handles user_id + emailOrPhone from mobile app
// =====================================================

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 for debugging
file_put_contents(__DIR__ . "log.txt", date("Y-m-d H:i:s") . " " . $rawInput . PHP_EOL, FILE_APPEND);

// Helper function 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"));
}

$action        = isset($input['action']) ? trim($input['action']) : '';
//$userId        = isset($input['user_id']) ? intval($input['user_id']) : 0;
$userId = isset($input['userId']) ? intval($input['userId']) : 0;
$emailOrPhone  = isset($input['emailOrPhone']) ? trim($input['emailOrPhone']) : '';

if ($userId <= 0 || $emailOrPhone === '') {
    respond(array("success" => false, "message" => "Invalid or missing user data"));
}

// =====================================================
// 1. CHECK IF USER HAS A TRANSACTION PIN
// =====================================================
if ($action === "check_transaction_pin") {
    try {
        $stmt = $pdo->prepare("SELECT transaction_pin FROM users WHERE id = :id OR email = :eop OR phone = :eop");
        $stmt->execute(array(':id' => $userId, ':eop' => $emailOrPhone));
        $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"));
        }
    } catch (Exception $e) {
        respond(array("success" => false, "message" => "Database error: " . $e->getMessage()));
    }
}

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

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

    try {
        $check = $pdo->prepare("SELECT transaction_pin FROM users WHERE id = :id OR email = :eop OR phone = :eop");
        $check->execute(array(':id' => $userId, ':eop' => $emailOrPhone));
        $existing = $check->fetch(PDO::FETCH_ASSOC);

        if ($existing && !empty($existing['transaction_pin'])) {
            respond(array("success" => false, "message" => "PIN already exists. Please change it instead."));
        }

        $pinDate = date("Y-m-d H:i:s");
        $nPin = md5($newPin);

        $update = $pdo->prepare("UPDATE users SET transaction_pin = :pin, transaction_pin_date = :pdate WHERE id = :id OR email = :eop OR phone = :eop");
        $update->execute(array(':pin' => $nPin, ':pdate' => $pinDate, ':id' => $userId, ':eop' => $emailOrPhone));

        if ($update->rowCount() > 0) {
            respond(array("success" => true, "message" => "PIN created successfully", "pin_date" => $pinDate));
        } else {
            respond(array("success" => false, "message" => "Failed to create PIN"));
        }
    } catch (Exception $e) {
        respond(array("success" => false, "message" => "Database error: " . $e->getMessage()));
    }
}

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

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

    try {
        $stmt = $pdo->prepare("SELECT transaction_pin FROM users WHERE id = :id OR email = :eop OR phone = :eop");
        $stmt->execute(array(':id' => $userId, ':eop' => $emailOrPhone));
        $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 !== md5($currentPin)) {
            respond(array("success" => false, "message" => "Current PIN is incorrect"));
        }

        $updateDate = date("Y-m-d H:i:s");
        $nPin = md5($newPin);

        $update = $pdo->prepare("UPDATE users SET transaction_pin = :pin, transaction_pin_date = :pdate WHERE id = :id OR email = :eop OR phone = :eop");
        $update->execute(array(':pin' => $nPin, ':pdate' => $updateDate, ':id' => $userId, ':eop' => $emailOrPhone));

        if ($update->rowCount() > 0) {
            respond(array("success" => true, "message" => "PIN changed successfully", "pin_date" => $updateDate));
        } else {
            respond(array("success" => false, "message" => "Failed to change PIN"));
        }
    } catch (Exception $e) {
        respond(array("success" => false, "message" => "Database error: " . $e->getMessage()));
    }
}

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