<?php
// Šis fails apstrādā PayPal maksājumu
session_start();
require 'db_conn.php';
// PayPal API piekļuves dati
$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ē un izveido datubāzes ierakstu par veiksmīgu pirkumu
$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;
// Groza dati tiek saglabāti order_items tabulā
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();
}
// Notīra grozu
$_SESSION['cart'] = [];

echo $result;