<?php
// checkout.php - M-Pesa payment processing with error handling
ob_start(); // Start output buffering
session_start();
error_log("Entering checkout.php: Session ID = " . session_id());

include_once 'config.php';
include_once 'auth.php';
require_once 'vendor/autoload.php'; // PHPMailer

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Log session data
error_log("Session data: " . json_encode($_SESSION));

// Fallback for display_flash_message if not defined
if (!function_exists('display_flash_message')) {
    error_log("display_flash_message() not defined, using fallback");
    function display_flash_message() {
        if (isset($_SESSION['flash_message'])) {
            $type = $_SESSION['flash_message']['type'] === 'success' ? 'success' : 'danger';
            $message = htmlspecialchars($_SESSION['flash_message']['message']);
            echo "<div class='alert alert-$type alert-dismissible fade show' role='alert'>
                    $message
                    <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                  </div>";
            unset($_SESSION['flash_message']);
        }
    }
}

if (!is_logged_in()) {
    error_log("User not logged in, redirecting to login.php");
    set_flash_message('error', 'Please log in to checkout.');
    header("Location: login.php?redirect=checkout");
    ob_end_flush();
    exit();
}
function set_flash_message($type, $message) {
    $_SESSION['flash_message'] = [
        'type' => $type,
        'message' => $message
    ];
}

function display_flash_message() {
    if (isset($_SESSION['flash_message'])) {
        $type = $_SESSION['flash_message']['type'] === 'success' ? 'success' : 'danger';
        $message = htmlspecialchars($_SESSION['flash_message']['message']);
        echo "<div class='alert alert-$type alert-dismissible fade show' role='alert'>
                $message
                <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
              </div>";
        unset($_SESSION['flash_message']);
    }
}
$cart = $_SESSION['cart'] ?? [];
error_log("Cart: " . json_encode($cart));
if (empty($cart)) {
    error_log("Cart is empty, redirecting to cart.php");
    set_flash_message('error', 'Your cart is empty.');
    header("Location: cart.php");
    ob_end_flush();
    exit();
}

// Calculate total and prepare order items
$total = 0;
$order_items = [];
$ids = implode(',', array_map('intval', array_keys($cart)));
error_log("Product IDs: $ids");

if (empty($ids)) {
    error_log("No valid product IDs, redirecting to cart.php");
    set_flash_message('error', 'Invalid cart items.');
    header("Location: cart.php");
    ob_end_flush();
    exit();
}

try {
    $stmt = $conn->prepare("SELECT id, name, price FROM products WHERE id IN ($ids)");
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $quantity = $cart[$row['id']];
        $subtotal = $row['price'] * $quantity;
        $total += $subtotal;
        $order_items[] = [
            'id' => $row['id'],
            'name' => $row['name'],
            'price' => $row['price'],
            'quantity' => $quantity
        ];
    }
    if (empty($order_items)) {
        throw new Exception("No products found for IDs: $ids");
    }
} catch (Exception $e) {
    error_log("Database error: " . $e->getMessage());
    set_flash_message('error', 'Error loading cart items: ' . htmlspecialchars($e->getMessage()));
    header("Location: cart.php");
    ob_end_flush();
    exit();
}
// Fetch user email and address
try {
    $stmt = $conn->prepare("SELECT email, address FROM users WHERE id = ?");
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    if (!$user) {
        throw new Exception("User not found for ID: " . $_SESSION['user_id']);
    }
    $user_email = $user['email'];
    $delivery_location = $user['address'] ?: 'Nairobi, Kenya'; // Default location
} catch (Exception $e) {
    error_log("User fetch error: " . $e->getMessage());
    set_flash_message('error', 'Error fetching user details.');
    header("Location: cart.php");
    ob_end_flush();
    exit();
}

// Handle payment initiation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['phone']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    $phone = preg_replace('/[^0-9]/', '', $_POST['phone']);
    error_log("Payment initiated: Phone = $phone");
    if (!preg_match('/^2547[0-9]{8}$/', $phone)) {
        set_flash_message('error', 'Invalid phone number. Use format +2547XXXXXXXX.');
    } else {
        try {
            // Calculate delivery date (3 days from now)
            $delivery_date = date('Y-m-d', strtotime('+3 days'));

            // Create order
            $stmt = $conn->prepare("INSERT INTO orders (user_id, total, status, delivery_date, delivery_location) VALUES (?, ?, 'pending', ?, ?)");
            $stmt->bind_param("idss", $_SESSION['user_id'], $total, $delivery_date, $delivery_location);
            if (!$stmt->execute()) {
                throw new Exception("Order creation failed: " . $conn->error);
            }
            $order_id = $conn->insert_id;
            error_log("Order created: ID = $order_id");

            // Insert order items
            $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
            foreach ($order_items as $item) {
                $stmt->bind_param("iiid", $order_id, $item['id'], $item['quantity'], $item['price']);
                if (!$stmt->execute()) {
                    throw new Exception("Order item insertion failed: " . $conn->error);
                }
            }

            // M-Pesa STK Push
            $consumer_key = getenv('MPESA_CONSUMER_KEY') ?: 'YOUR_CONSUMER_KEY';
            $consumer_secret = getenv('MPESA_CONSUMER_SECRET') ?: 'YOUR_CONSUMER_SECRET';
            $shortcode = '174379';
            $passkey = 'YOUR_PASSKEY';
            $timestamp = date('YmdHis');
            $password = base64_encode($shortcode . $passkey . $timestamp);
            $access_token = get_mpesa_access_token($consumer_key, $consumer_secret);
            $stk_push_data = [
                'BusinessShortCode' => $shortcode,
                'Password' => $password,
                'Timestamp' => $timestamp,
                'TransactionType' => 'CustomerPayBillOnline',
                'Amount' => $total,
                'PartyA' => $phone,
                'PartyB' => $shortcode,
                'PhoneNumber' => $phone,
                'CallBackURL' => 'http://your-domain.com/callback.php',
                'AccountReference' => 'Order' . $order_id,
                'TransactionDesc' => 'Payment for Order #' . $order_id
            ];

            // Simulate M-Pesa API call (for local testing)
            $response = ['ResultCode' => 0]; // Simulated success
            // Uncomment for live M-Pesa API
            /*
            $ch = curl_init('https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest');
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Authorization: Bearer ' . $access_token,
                'Content-Type: application/json'
            ]);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($stk_push_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $response = json_decode(curl_exec($ch), true);
            curl_close($ch);
            */

            if ($response['ResultCode'] === 0) {
                // Update order status
                $stmt = $conn->prepare("UPDATE orders SET status = 'completed' WHERE id = ?");
                $stmt->bind_param("i", $order_id);
                if (!$stmt->execute()) {
                    throw new Exception("Order status update failed: " . $conn->error);
                }

                // Send email
                try {
                    $mail = new PHPMailer(true);
                    $mail->isSMTP();
                    $mail->Host = 'smtp.office365.com';
                    $mail->SMTPAuth = true;
                    $mail->Username = getenv('EMAIL_USERNAME') ?: 'your_email@your-domain.com';
                    $mail->Password = getenv('EMAIL_PASSWORD') ?: 'your_password';
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                    $mail->Port = 587;

                    $mail->setFrom('your_email@your-domain.com', 'Doyle Enterprise');
                    $mail->addAddress($user_email);
                    $mail->isHTML(true);
                    $mail->Subject = 'Order Confirmation - Doyle Enterprise';
                    $items_list = '';
                    foreach ($order_items as $item) {
                        $items_list .= "<li>{$item['name']} (x{$item['quantity']}) - KES " . number_format($item['price'] * $item['quantity'], 2) . "</li>";
                    }
                    $mail->Body = "
                        <h2>Order Confirmation</h2>
                        <p>Dear Customer,</p>
                        <p>Your order #{$order_id} has been received and payment confirmed.</p>
                        <h3>Order Details:</h3>
                        <ul>$items_list</ul>
                        <p><strong>Total:</strong> KES " . number_format($total, 2) . "</p>
                        <p><strong>Delivery Date:</strong> " . htmlspecialchars($delivery_date) . "</p>
                        <p><strong>Delivery Location:</strong> " . htmlspecialchars($delivery_location) . "</p>
                        <p>Thank you for shopping with Doyle Enterprise!</p>
                    ";
                    $mail->send();
                    error_log("Email sent to $user_email for order #$order_id");
                } catch (Exception $e) {
                    error_log("Email sending failed: " . $mail->ErrorInfo);
                    set_flash_message('error', 'Order completed but email sending failed.');
                }

                unset($_SESSION['cart']);
                set_flash_message('success', 'Payment successful! Order #' . $order_id . ' confirmed.');
                error_log("Payment successful, order #$order_id completed");
                header("Location: orders.php");
                ob_end_flush();
                exit();
            } else {
                set_flash_message('error', 'Payment failed. Please try again.');
                error_log("Payment failed: " . json_encode($response));
            }
        } catch (Exception $e) {
            error_log("Payment processing error: " . $e->getMessage());
            set_flash_message('error', 'Error processing payment: ' . htmlspecialchars($e->getMessage()));
        }
    }
}
// Generate CSRF token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
error_log("CSRF token generated: " . $_SESSION['csrf_token']);

// M-Pesa Access Token Function
function get_mpesa_access_token($consumer_key, $consumer_secret) {
    $ch = curl_init('https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials');
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Basic ' . base64_encode($consumer_key . ':' . $consumer_secret)]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = json_decode(curl_exec($ch), true);
    curl_close($ch);
    error_log("M-Pesa access token: " . ($response['access_token'] ?? 'Failed'));
    return $response['access_token'] ?? '';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout - Doyle Enterprise</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <?php include_once 'header.php'; ?>
    <div class="container mt-4">
        <h2 class="text-center mb-4">Checkout</h2>
        <?php display_flash_message(); ?>
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Order Summary</h5>
                        <ul class="list-group list-group-flush">
                            <?php foreach ($order_items as $item): ?>
                                <li class="list-group-item d-flex justify-content-between">
                                    <span><?php echo htmlspecialchars($item['name']); ?> (x<?php echo $item['quantity']; ?>)</span>
                                    <span>KES <?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                                </li>
                            <?php endforeach; ?>
                            <li class="list-group-item d-flex justify-content-between fw-bold">
                                <span>Total</span>
                                <span>KES <?php echo number_format($total, 2); ?></span>
                            </li>
                        </ul>
                        <button type="button" class="btn btn-primary mt-3 w-100" data-bs-toggle="modal" data-bs-target="#paymentModal">Proceed to Payment</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="paymentModalLabel">M-Pesa Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="post">
                        <div class="mb-3">
                            <label for="phone" class="form-label">Phone Number (e.g., +2547XXXXXXXX)</label>
                            <input type="text" class="form-control" id="phone" name="phone" placeholder="+2547XXXXXXXX" required>
                        </div>
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <button type="submit" class="btn btn-primary w-100">Pay Now</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <?php include_once 'footer.php'; ?>
</body>
</html>
<?php ob_end_flush(); ?>