<?php
session_start();

if (!isset($_SESSION['mobile']) || !isset($_SESSION['otp'])) {
    header('Location: http://localhost/online_goods/index.php');
    exit;
}

include("configa.php");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // ইউজার ইনপুট ভ্যালিডেশন
    $discount_code = mysqli_real_escape_string($conn, $_POST['discount_code']);

    // ডিসকাউন্ট কোড খোঁজা
    $sql = "SELECT * FROM discount WHERE discount_code = ?";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        echo json_encode(["status" => "error", "message" => "Query prepare ব্যর্থ হয়েছে।"]);
        exit;
    }

    $stmt->bind_param("s", $discount_code);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // ডিসকাউন্ট কোড সঠিক
        $discount = $result->fetch_assoc();

      echo json_encode(["status" => "success", "message" => "অর্ডার সফলভাবে সাবমিট হয়েছে। ডিসকাউন্ট প্রয়োগ হয়েছে।", "discountCode" => $discount['discount_code'], "discountPresent" => $discount['discount_present'] ]);
      
    } else {
        echo json_encode(["status" => "invalid", "message" => "ডিসকাউন্ট কোড সঠিক নয়।"]);
    }

    $stmt->close();
    $conn->close();
}
?>
