<?php
session_start();
require_once 'db/config.php';

if (isset($_POST['coupon_code']) && !empty($_POST['coupon_code'])) {
    $coupon_code = trim($_POST['coupon_code']);

    $pdo = db();
    $stmt = $pdo->prepare("SELECT * FROM coupons WHERE code = ? AND is_active = 1");
    $stmt->execute([$coupon_code]);
    $coupon = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($coupon) {
        $_SESSION['coupon_id'] = $coupon['id'];
        $_SESSION['coupon_code'] = $coupon['code'];
        $_SESSION['discount_percentage'] = $coupon['discount_percentage'];
        unset($_SESSION['coupon_error']);
    } else {
        $_SESSION['coupon_error'] = "Invalid or expired coupon code.";
        unset($_SESSION['coupon_id']);
        unset($_SESSION['coupon_code']);
        unset($_SESSION['discount_percentage']);
    }
} else {
    $_SESSION['coupon_error'] = "Please enter a coupon code.";
}

header("Location: cart.php");
exit();