<?php
session_start();
$conn = new mysqli("localhost", "kkfxoaad", "Bitok@2025", "kkfxoaad_bella");

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

$name     = $data['name'];
$phone    = $data['phone'];
$address  = $data['address'];
$notes    = $data['notes'];
$tip      = $data['tip'];
$shipping = $data['shipping'];

// Get cart from session
$cart = $_SESSION['cart'] ?? [];

// Calculate subtotal
$subtotal = 0;
foreach ($cart as $item) {
  $subtotal += $item['price'] * $item['quantity'];
}
$total = $subtotal + $shipping + $tip;

// 1. Save checkout attempt
$stmt = $conn->prepare("INSERT INTO checkout_attempts (user_id, name, phone, address, notes, subtotal, shipping, tip, total) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$userId = $_SESSION['user_id'] ?? null;
$stmt->bind_param("issssddds", $userId, $name, $phone, $address, $notes, $subtotal, $shipping, $tip, $total);
$stmt->execute();
$attemptId = $stmt->insert_id;

// 2. Save items
$itemStmt = $conn->prepare("INSERT INTO checkout_items (attempt_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
foreach ($cart as $item) {
  $itemStmt->bind_param("iiid", $attemptId, $item['id'], $item['quantity'], $item['price']);
  $itemStmt->execute();
}

// TODO: Initiate Kopokopo STK push here using $phone and $total

echo "Checkout logged. Proceeding to payment...";
