<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json");

require_once "../../dbcon.php";
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    exit(0);
}


/* --------------------------------
SANITIZER
---------------------------------*/
function clean($data)
{
    global $conn;
    return htmlspecialchars(strip_tags(mysqli_real_escape_string($conn, $data)));
}

/* --------------------------------
PROFESSIONAL PAYMENT NOTES
---------------------------------*/
function getPaymentNote($status)
{
    switch ($status) {
        case 'submitted':
            return "Payment proof submitted by customer for verification.";
        case 'confirmed':
            return "Payment verified and confirmed successfully.";
        case 'rejected':
            return "Payment rejected due to invalid or insufficient proof.";
        case 'failed':
            return "Payment marked as failed.";
        default:
            return "Payment status updated.";
    }
}

/* --------------------------------
ADD PAYMENT HISTORY (OPTIONAL)
---------------------------------*/
function addPaymentHistory($order_id, $note)
{
    global $conn;
    $order_id = clean($order_id);
    $note = clean($note);

    mysqli_query(
        $conn,
        "INSERT INTO order_history (order_id, status, note)
                VALUES ('$order_id', 'payment', '$note')"
    );
}

$method = $_SERVER["REQUEST_METHOD"];

/* --------------------------------
CREATE PAYMENT (USER)
---------------------------------*/
if ($method === "POST" && isset($_GET["create"])) {

    if (!isset($_FILES['receipt_image'])) {
        echo json_encode(["status" => "error", "message" => "Receipt image is required"]);
        exit;
    }

    $order_id = clean($_POST['order_id'] ?? '');
    $car_id = clean($_POST['car_id'] ?? '');
    $user_id = clean($_POST['user_id'] ?? '');
    $amount = clean($_POST['amount'] ?? '');
    $payment_type = clean($_POST['payment_type'] ?? '');
    $transaction_id = clean($_POST['transaction_id'] ?? '');

    if (!$order_id || !$car_id || !$user_id || !$amount || !$payment_type) {
        echo json_encode(["status" => "error", "message" => "Required fields missing"]);
        exit;
    }

    /* -------- Upload Receipt -------- */
    $uploadDir = "../../assets/payments/";
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $ext = pathinfo($_FILES['receipt_image']['name'], PATHINFO_EXTENSION);
    $fileName = "PAY_" . time() . "_" . rand(1000, 9999) . "." . $ext;
    $targetPath = $uploadDir . $fileName;

    if (!move_uploaded_file($_FILES['receipt_image']['tmp_name'], $targetPath)) {
        echo json_encode(["status" => "error", "message" => "Receipt upload failed"]);
        exit;
    }

    $q = "INSERT INTO payments 
                (order_id, car_id, user_id, amount, payment_type, transaction_id, receipt_image, status, submitted_at)
                VALUES 
                ('$order_id', '$car_id', '$user_id', '$amount', '$payment_type', '$transaction_id', '$fileName', 'submitted', NOW())";

    if (!mysqli_query($conn, $q)) {
        echo json_encode(["status" => "error", "message" => mysqli_error($conn)]);
        exit;
    }

    addPaymentHistory($order_id, getPaymentNote('submitted'));

    echo json_encode([
        "status" => "success",
        "message" => "Payment submitted successfully"
    ]);
    exit;
}

/* --------------------------------
GET PAYMENTS BY USER
---------------------------------*/
if ($method === "GET" && isset($_GET["user"])) {
    $user_id = clean($_GET["user"]);

    $q = "SELECT p.*, o.order_number, c.name AS car_name
                FROM payments p
                JOIN orders o ON o.id = p.order_id
                JOIN cars c ON c.id = p.car_id
                WHERE p.user_id='$user_id'
                ORDER BY p.created_at DESC";

    $res = mysqli_query($conn, $q);
    $rows = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $rows[] = $row;
    }

    echo json_encode(["status" => "success", "data" => $rows]);
    exit;
}

/* --------------------------------
GET PAYMENTS BY ORDER
---------------------------------*/
if ($method === "GET" && isset($_GET["order"])) {
    $order_id = clean($_GET["order"]);

    $q = "SELECT *
                FROM payments
                WHERE order_id='$order_id'
                ORDER BY created_at DESC";

    $res = mysqli_query($conn, $q);
    $rows = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $rows[] = $row;
    }

    echo json_encode(["status" => "success", "data" => $rows]);
    exit;
}

/* --------------------------------
GET ALL PAYMENTS (ADMIN)
---------------------------------*/
if ($method === "GET" && isset($_GET["all"])) {
    $agent_id = isset($_GET['agent_id']) ? intval($_GET['agent_id']) : null;
    $where = "";
    if ($agent_id) {
        $where = " WHERE u.agent_id = $agent_id ";
    }

    $q = "SELECT 
                    p.*,
                    u.full_name AS user_name,
                    a.full_name AS verified_by_name,
                    o.order_number,
                    c.name AS car_name,
                    c.model AS model
                FROM payments p
                JOIN users u ON u.id = p.user_id
                JOIN orders o ON o.id = p.order_id
                JOIN cars c ON c.id = p.car_id
                LEFT JOIN users a ON a.id = p.verified_by
                $where
                ORDER BY p.created_at DESC";

    $res = mysqli_query($conn, $q);
    $rows = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $rows[] = $row;
    }

    echo json_encode(["status" => "success", "data" => $rows]);
    exit;
}

/* --------------------------------
VERIFY / REJECT PAYMENT (ADMIN)
---------------------------------*/
/* --------------------------------
VERIFY / REJECT PAYMENT (ADMIN)
---------------------------------*/
if ($method === "PUT" && isset($_GET["verify"])) {

    $data = json_decode(file_get_contents("php://input"), true);

    $payment_id = clean($data["payment_id"] ?? '');
    $status = clean($data["status"] ?? '');
    $admin_id = clean($data["admin_id"] ?? '');

    if (!$payment_id || !$status || !$admin_id) {
        echo json_encode(["status" => "error", "message" => "Missing verification data"]);
        exit;
    }

    if (!in_array($status, ['pending', 'submitted', 'confirmed', 'rejected', 'failed'])) {
        echo json_encode(["status" => "error", "message" => "Invalid payment status"]);
        exit;
    }

    // Get payment info
    $res = mysqli_query($conn, "SELECT order_id, user_id FROM payments WHERE id='$payment_id'");
    $payment = mysqli_fetch_assoc($res);
    if (!$payment) {
        echo json_encode(["status" => "error", "message" => "Payment not found"]);
        exit;
    }

    $order_id = $payment['order_id'];
    $user_id = $payment['user_id'];

    // Determine new order status & payment_status
    $order_status = 'pending';
    $order_payment_status = 'pending';

    if ($status === 'confirmed') {
        $order_status = 'approved';
        $order_payment_status = 'paid';
    } elseif ($status === 'rejected' || $status === 'failed') {
        $order_status = 'pending';
        $order_payment_status = 'pending';
    } elseif ($status === 'submitted') {
        $order_status = 'pending';
        $order_payment_status = 'partial';
    }

    // Start transaction
    mysqli_begin_transaction($conn);

    try {
        // Update payment
        $q1 = "UPDATE payments
               SET status='$status',
                   verified_by='$admin_id',
                   verified_at=NOW()
               WHERE id='$payment_id'";
        if (!mysqli_query($conn, $q1)) {
            throw new Exception(mysqli_error($conn));
        }

        // Update order
        $q2 = "UPDATE orders
               SET status='$order_status',
                   payment_status='$order_payment_status',
                   updated_at=NOW()
               WHERE id='$order_id'";
        if (!mysqli_query($conn, $q2)) {
            throw new Exception(mysqli_error($conn));
        }

        // Add to order_history
        $note_safe = mysqli_real_escape_string($conn, "Payment status changed to '{$status}' by admin ID {$admin_id}");
        $q3 = "INSERT INTO order_history (order_id, status, changed_by, note, changed_at)
               VALUES ('$order_id', '$order_status', '$admin_id', '$note_safe', NOW())";
        if (!mysqli_query($conn, $q3)) {
            throw new Exception(mysqli_error($conn));
        }

        // Commit transaction
        mysqli_commit($conn);

        echo json_encode([
            "status" => "success",
            "message" => "Payment {$status} successfully",
            "payment_id" => $payment_id,
            "order_id" => $order_id,
            "user_id" => $user_id
        ]);
    } catch (Exception $e) {
        mysqli_rollback($conn);
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }

    exit;
}



/* --------------------------------
FALLBACK
---------------------------------*/
echo json_encode([
    "status" => "error",
    "message" => "Invalid API request"
]);
exit;
