<?php
// Include DB connection
include './db.php';

// Start session
session_start();

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit();
}

$user_id = $_SESSION['user_id']; // Get user ID

// Query to get the user's balance
$stmt = $conn->prepare("SELECT saldo, phone FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($user_balance, $phone_number);
$stmt->fetch();
$stmt->close();

// Get total cart price
$stmt = $conn->prepare("SELECT SUM(price) FROM cart WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($total_price);
$stmt->fetch();
$stmt->close();

// Check if user has enough balance
if ($user_balance >= $total_price) {
    // Generate invoice number (can be based on date and user ID or other logic)
    $invoice_number = 'INV-' . strtoupper(uniqid($user_id . '-'));

    // Start transaction for processing
    $conn->begin_transaction();

    try {
        // Insert into transactions table
        $stmt = $conn->prepare("INSERT INTO transactions (invoice_number, user_id, total_price, status) VALUES (?, ?, ?, 'completed')");
        $stmt->bind_param("sdi", $invoice_number, $user_id, $total_price);
        $stmt->execute();
        $transaction_id = $stmt->insert_id; // Get the last inserted transaction ID
        $stmt->close();

        // Move cart items to transaction_details table
        $stmt = $conn->prepare("INSERT INTO transaction_details (transaction_id, machine_id, machine_type, price) SELECT ?, machine_id, machine_type, price FROM cart WHERE user_id = ?");
        $stmt->bind_param("ii", $transaction_id, $user_id);
        $stmt->execute();
        $stmt->close();

        // Delete cart items after transaction
        $stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $stmt->close();

        // Deduct balance from the user
        $new_balance = $user_balance - $total_price;
        $stmt = $conn->prepare("UPDATE users SET saldo = ? WHERE id = ?");
        $stmt->bind_param("di", $new_balance, $user_id);
        $stmt->execute();
        $stmt->close();

        // Commit transaction
        $conn->commit();

        // Fetch purchased items from transaction_details
        $stmt = $conn->prepare("SELECT machine_id, machine_type, price FROM transaction_details WHERE transaction_id = ?");
        $stmt->bind_param("i", $transaction_id);
        $stmt->execute();
        $stmt->bind_result($machine_id, $machine_type, $item_price);

        $items_message = "\nItems Purchased:\n";
        while ($stmt->fetch()) {
            $items_message .= "- ID: " . htmlspecialchars($machine_id) . " | " . htmlspecialchars($machine_type) . " (Rp " . number_format($item_price, 0, ',', '.') . ")\n";
        }
        $stmt->close();

        // Prepare the message
        $message = "Transaction Successful!\n\n";
        $message .= "Invoice Number: " . $invoice_number . "\n";
        $message .= "Total Price: Rp " . number_format($total_price, 0, ',', '.') . "\n";
        $message .= "Status: Completed\n";
        $message .= $items_message; // Add the list of items to the message
        $message .= "\nThank you for your purchase!";

        // Send message to WhatsApp using Wablas API
        $curl = curl_init();
        $token = "uWzy4b39nOywBtLBwp6OwZRX0ARBXswLd0FXryqDDvIsmnQKNynW9c1jlfx4oJB6"; // Replace with your Wablas API token
        $data = [
            'phone' => $phone_number,
            'message' => $message,
        ];

        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: $token"));
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($curl, CURLOPT_URL, "https://kudus.wablas.com/api/send-message");
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        $result = curl_exec($curl);
        curl_close($curl);

        // Update machine command status to 'ON' after the transaction, using serialNumber
        $stmt = $conn->prepare("
            UPDATE machine 
            SET command = 'ON' 
            WHERE serialNumber IN 
            (SELECT machine_id FROM transaction_details WHERE transaction_id = ?)
        ");
        $stmt->bind_param("i", $transaction_id);
        $stmt->execute();
        $stmt->close();

        // Send JSON response with success and the invoice number
        echo json_encode([
            'success' => true,
            'message' => 'Transaction processed successfully.',
            'invoice_number' => $invoice_number
        ]);
        exit(); // Make sure no further code is executed after the response

    } catch (Exception $e) {
        // Rollback if any error occurs
        $conn->rollback();

        // Respond with failure
        echo json_encode(['success' => false, 'message' => 'An error occurred while processing your transaction.']);
    }
} else {
    // Respond if user doesn't have enough balance
    echo json_encode(['success' => false, 'message' => 'Insufficient balance for the transaction.']);
}

$conn->close();
?>