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

// PayPal maksājums
if (isset($_POST['paypal_success'])) {

    $user_id = $_SESSION['user_id'] ?? null;

    if (!$user_id) {
        http_response_code(403);
        exit("Not logged in");
    }

    if (empty($_SESSION['cart'])) {
        exit("Cart empty");
    }

    // izveido pasūtījumu 
    $stmt = $conn->prepare("INSERT INTO orders (user_id, status) VALUES (?, 'complete')");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $order_id = $stmt->insert_id;
    $stmt->close();

    // Ievieto preces
    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();
        $stmt->close();
    }

    // Izdzēš grozu
    $_SESSION['cart'] = [];

    exit("OK");
}

// Groza aktivizācija
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// Pievieno preci
if (isset($_GET['add'])) {
    $product_id = (int)$_GET['add'];
    $_SESSION['cart'][$product_id] = ($_SESSION['cart'][$product_id] ?? 0) + 1;
    header("Location: cart.php");
    exit;
}

// Dzēš preci
if (isset($_GET['remove'])) {
    $product_id = (int)$_GET['remove'];
    unset($_SESSION['cart'][$product_id]);
    header("Location: cart.php");
    exit;
}

// Atjaunina produkta statusu
if (isset($_POST['update'])) {
    foreach ($_POST['quantity'] as $product_id => $qty) {
        $qty = (int)$qty;
        if ($qty <= 0) {
            unset($_SESSION['cart'][$product_id]);
        } else {
            $_SESSION['cart'][$product_id] = min($qty, 1000);
        }
    }
    header("Location: cart.php");
    exit;
}

// Iegūst visas preces no groza
$cart_items = [];
$total = 0;

if (!empty($_SESSION['cart'])) {
    $ids = implode(',', array_map('intval', array_keys($_SESSION['cart'])));
    $result = $conn->query("SELECT * FROM products WHERE id IN ($ids)");
    while ($row = $result->fetch_assoc()) {
        $cart_items[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="lv">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Jūsu Grozs</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"/>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="main.css"/>
<script src="script.js"></script>

<!--  PAYPAL SDK (SANDBOX) -->
<script src="https://www.sandbox.paypal.com/sdk/js?client-id=AXtjsn6XKHPOOx5Voj_Ip_R8BIvv_NGXCQTtkB9nzfNWSHwYNay8V4u5urSURhXYhER4UuSACmz1bDfS&currency=EUR"></script>
</head>

<body class="page-layout">

<header>
  <input type="checkbox" id="toggler" />
  <label for="toggler" class="fa fa-bars"></label>

  <a href="index.php" class="logo">Ziedu internetveikals<span>🌷</span></a>

<nav class="navbar">
  <div class="dropdown-nav">
    <a href="katalogs.php" class="dropbtn-nav">Katalogs</a>

    <div class="dropdown-content-nav">
      <a href="ziedi.php">Ziedi</a>
      <a href="telpaugi.php">Telpaugi</a>
      <a href="eksotiskieaugi.php">Eksotiskie augi</a>
    </div>
  </div>
</nav>

  <div class="search-container">
    <form action="katalogs.php" method="GET">
      <input type="text" name="q" placeholder="Meklēt">
      <button type="submit"><i class="fa fa-search"></i></button>
    </form>
  </div>

  <div class="icons">
    <a href="cart.php" class="fas fa-shopping-cart"></a>
    <button type="button" class="fas fa-search mobile-search-toggle"></button>

    <div class="dropdown">
      <?php if (isset($_SESSION['email'])): ?>
        <a href="profile.php" class="fas fa-user dropbtn"></a>
      <?php else: ?>
        <a href="#" class="fas fa-user dropbtn"></a>
      <?php endif; ?>

      <div class="dropdown-content">
        <?php if (isset($_SESSION['email'])): ?>
          <a href="logout.php" class="logout">Izrakstīties</a>
        <?php else: ?>
          <a href="login.html">Pieslēgties</a>
          <a href="register.html">Reģistrēties</a>
        <?php endif; ?>
      </div>
    </div>
  </div>
</header>

<main class="page-content">
<h2 class="catalog-title">🛒 Jūsu Grozs</h2>

<?php if (!empty($cart_items)): ?>
<form method="post">

<div class="catalog-grid">
<?php foreach ($cart_items as $item): 
  $product_id = $item['id'];
  $qty = $_SESSION['cart'][$product_id];
  $subtotal = $item['price'] * $qty;
  $total += $subtotal;
?>
<div class="catalog-card">
  <img src="<?= PRODUCT_IMAGE_PATH . htmlspecialchars($item['image']) ?>" alt="<?= htmlspecialchars($item['name']) ?>">
  <div class="catalog-body">
    <h3><?= htmlspecialchars($item['name']) ?></h3>
    <p class="catalog-price"><?= number_format($item['price'],2) ?> €</p>

    <div class="cart-quantity">
      <label>Daudzums:</label>
      <input type="number" name="quantity[<?= $product_id ?>]" value="<?= $qty ?>" min="1" max="1000">
    </div>

    <button type="submit" name="update" class="catalog-btn">Atjaunināt daudzumu</button>
    <a href="cart.php?remove=<?= $product_id ?>" class="catalog-btn remove-btn">Noņemt</a>
  </div>
</div>
<?php endforeach; ?>
</div>

<h3 class="cart-total">Kopā: <?= number_format($total,2) ?> €</h3>

</form>

<!-- PayPal poga -->
<div id="paypal-button-container" style="margin-top:20px;"></div>

<script>
paypal.Buttons({
fundingSource: paypal.FUNDING.PAYPAL,
  createOrder: function(data, actions) {
    return fetch("create_order.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: "total=<?= number_format($total,2,'.','') ?>"
    })
    .then(res => res.json())
    .then(data => data.id);
  },

  onApprove: function(data, actions) {
    return fetch("capture_order.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: "orderID=" + data.orderID
    })
    .then(res => res.json())
    .then(() => {
      window.location.href = "success.php";
    });
  }

}).render('#paypal-button-container');
</script>

<?php else: ?>
<p class="cart-empty">
  Jūsu grozs ir tukšs. <a href="katalogs.php" class="catalog-link">Dodieties uz katalogu</a>
</p>
<?php endif; ?>

</main>

<footer>
  <div class="footer-container">
    <div class="footer-left">
      <a href="parmums.php">Par mums</a>
      <a href="kontakti.php">Kontakti</a>
    </div>
  </div>
</footer>

</body>
</html>
