<?php
session_start();

// =====================
// Database connection
// =====================
require_once 'db_connect.php'; // Ndio hii update ya dbcon
if ($conn->connect_error) {
    die("DB Connection failed: " . $conn->connect_error);
}

// =====================
// Handle form submission
// =====================
$payment_message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = trim($_POST['phone']);
    $amount = $_POST['amount'];

    // Save checkout attempt
    $stmt = $conn->prepare("INSERT INTO checkout_attempts (user_id, amount, status) VALUES (?, ?, 'pending')");
    $stmt->bind_param("id", $_SESSION['user_id'], $amount);
    $stmt->execute();
    $attemptId = $stmt->insert_id;
    $stmt->close();

    // =====================
    // KopoKopo Credentials
    // =====================
    $client_id     = "YOUR_CLIENT_ID";
    $client_secret = "YOUR_CLIENT_SECRET";
    $till_number   = "YOUR_TILL_NUMBER";
    $api_base      = "https://sandbox.kopokopo.com"; // change later for production

    // 1. Get Access Token
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_base . "/oauth/token");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        "client_id"     => $client_id,
        "client_secret" => $client_secret,
        "grant_type"    => "client_credentials"
    ]));
    $token_response = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (!isset($token_response['access_token'])) {
        $payment_message = "❌ Failed to connect to Kopokopo.";
    } else {
        $access_token = $token_response['access_token'];

        // 2. Send STK Push
        $stk_payload = [
            "payment_channel" => "M-PESA STK Push",
            "till_number"     => $till_number,
            "first_name"      => $_SESSION['name'] ?? "Customer",
            "last_name"       => "",
            "phone_number"    => $phone,
            "amount"          => $amount,
            "currency"        => "KES",
            "callback_url"    => "https://savannahsystems.co.ke/Bella/kopokopo_callback.php"
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_base . "/api/v1/payments");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $access_token",
            "Content-Type: application/json"
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($stk_payload));
        $response = curl_exec($ch);
        curl_close($ch);

        // Save to DB
        $ref = uniqid("TXN_");
        $stmt = $conn->prepare("INSERT INTO kopokopo_transactions (attempt_id, transaction_reference, amount, phone, response) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("isdss", $attemptId, $ref, $amount, $phone, $response);
        $stmt->execute();
        $stmt->close();

        $payment_message = "✅ STK push sent. Please check your phone.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>KopoKopo Payment</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    body {margin:0;font-family:'Segoe UI',sans-serif;background:#000;color:#fff;}
    header,footer{background:rgba(17,17,17,0.8);padding:15px 30px;}
    .container{max-width:500px;margin:40px auto;background:rgba(255,255,255,0.1);padding:20px;border-radius:10px;}
    input,button{width:100%;padding:12px;margin:10px 0;border:none;border-radius:6px;}
    input{background:#fff;color:#000;}
    button{background:#444;color:#fff;cursor:pointer;}
    button:hover{background:#666;}
    .message{text-align:center;margin:15px 0;}
  </style>
</head>
<body>

<!-- Header -->
<header>
  <div class="header-left">
    <a href="/Bella/index.php" class="logo"><img src="/Bella/images/TAJI YETU.png" alt="Logo" style="height:40px;"></a>
  </div>
</header>

<!-- Payment Container -->
<div class="container">
  <h2>Complete Your Payment</h2>
  <form method="POST">
    <label for="amount">Amount (KES)</label>
    <input type="text" name="amount" value="<?php echo $_SESSION['cart_total'] ?? '0'; ?>" readonly>

    <label for="phone">M-PESA Phone Number</label>
    <input type="text" name="phone" placeholder="07XXXXXXXX" required>

    <button type="submit">Pay with M-PESA</button>
  </form>

  <?php if ($payment_message): ?>
    <div class="message"><?php echo $payment_message; ?></div>
  <?php endif; ?>
</div>

<!-- Footer -->
<footer>
  <div class="social-icons">
    <a href="https://www.facebook.com/share/19B3wm2Xdn/"><i class="fab fa-facebook-f"></i></a>
    <a href="https://x.com/BellaGidds"><i class="fab fa-twitter"></i></a>
    <a href="https://www.instagram.com/belagids"><i class="fab fa-instagram"></i></a>
    <a href="https://www.tiktok.com/@belagids"><i class="fab fa-tiktok"></i></a>
  </div>
  <div class="copyright">
    &copy; 2025 TAJI YETU. All rights reserved.
  </div>
</footer>

</body>
</html>
