<?php
session_start();
require 'db_conn.php';

$client_id = "AXtjsn6XKHPOOx5Voj_Ip_R8BIvv_NGXCQTtkB9nzfNWSHwYNay8V4u5urSURhXYhER4UuSACmz1bDfS";
$secret = "EKC6CJ7SflaTi7zBbKIY3fJB3rat6R-UfaUQDQHk9_y-f86zzt1sZMZ50y1WA5jDW0s5-vRcDMglkdGD";

// Iegūst piekļuves pilnvaru
$ch = curl_init("https://api-m.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$client_id:$secret");
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

$response = json_decode(curl_exec($ch));
$access_token = $response->access_token;

// Apstiprināt maksājumu
$orderID = $_POST['orderID'];

$ch = curl_init("https://api-m.sandbox.paypal.com/v2/checkout/orders/$orderID/capture");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer $access_token"
]);

$result = curl_exec($ch);

// Saglabā pasūtījumu datubāzē
$user_id = $_SESSION['user_id'];

$stmt = $conn->prepare("INSERT INTO orders (user_id, status) VALUES (?, 'complete')");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$order_id = $stmt->insert_id;

foreach ($_SESSION['cart'] as $product_id => $qty) {
    $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity) VALUES (?, ?, ?)");
    $stmt->bind_param("iii", $order_id, $product_id, $qty);
    $stmt->execute();
}

$_SESSION['cart'] = [];

echo $result;