<?php
/**
 * promo_code_redeem.php
 * User Promo-Code দিলে, Verify করে, Balance-এ Bonus যোগ করে
 */
// ✅ ঠিক করা হলো — Error এখন সরাসরি Display না হয়ে, JSON-Response-এর
// ভেতরেই আসবে (আগে PHP-Error, JSON-এর সাথে মিশে গিয়ে পুরো Response
// Invalid করে দিচ্ছিল, তাই Frontend সবসময় Generic-Message দেখাতো)
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

set_error_handler(function($errno, $errstr, $errfile, $errline) {
    echo json_encode(['code' => 1, 'msg' => "PHP-Error: $errstr (Line: $errline)"]);
    exit;
});
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message'] . " (Line: " . $error['line'] . ")"]);
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$author = $bearer[1] ?? '';
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (($data_auth['status'] ?? '') !== 'Success') {
    echo json_encode(['code' => 1, 'msg' => 'Login করা নেই']);
    exit;
}

$userId = $data_auth['payload']['id'];
$input = json_decode(file_get_contents('php://input'), true);
$promoCode = strtoupper(trim($input['code'] ?? ''));

if ($promoCode === '') {
    echo json_encode(['code' => 1, 'msg' => 'Promo-Code লেখো']);
    exit;
}

// ✅ ধাপ ১ — Code Valid, Active, এখনো Usage-Limit পার হয়নি কিনা Check
$stmt = $conn->prepare("SELECT id, bonus_amount, usage_limit, used_count, expiry_date, is_active FROM promo_codes WHERE code = ? LIMIT 1");
$stmt->bind_param("s", $promoCode);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['code' => 1, 'msg' => 'ভুল Promo-Code, এই নামে কিছু পাওয়া যায়নি']);
    exit;
}

$promo = $result->fetch_assoc();

if (!$promo['is_active']) {
    echo json_encode(['code' => 1, 'msg' => 'এই Promo-Code এখন Active নেই']);
    exit;
}
if ($promo['expiry_date'] && strtotime($promo['expiry_date']) < time()) {
    echo json_encode(['code' => 1, 'msg' => 'এই Promo-Code-এর মেয়াদ শেষ হয়ে গেছে']);
    exit;
}
if ($promo['used_count'] >= $promo['usage_limit']) {
    echo json_encode(['code' => 1, 'msg' => 'এই Promo-Code-এর সব Use শেষ হয়ে গেছে']);
    exit;
}

// ✅ ধাপ ২ — এই User আগে এই Code ব্যবহার করেছে কিনা Check (Duplicate আটকানো)
$checkStmt = $conn->prepare("SELECT id FROM promo_code_usage WHERE code = ? AND user_id = ? LIMIT 1");
$checkStmt->bind_param("ss", $promoCode, $userId);
$checkStmt->execute();
if ($checkStmt->get_result()->num_rows > 0) {
    echo json_encode(['code' => 1, 'msg' => 'তুমি আগেই এই Code ব্যবহার করেছো']);
    exit;
}

// ✅ ধাপ ৩ — সবকিছু ঠিক থাকলে, Bonus দেওয়া (Transaction-Safe)
$conn->begin_transaction();
try {
    $bonusAmount = (float)$promo['bonus_amount'];

    // Balance-এ Bonus যোগ করা
    $updateStmt = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
    $updateStmt->bind_param("ds", $bonusAmount, $userId);
    $updateStmt->execute();
    if ($updateStmt->affected_rows <= 0) {
        throw new Exception('Balance Update ব্যর্থ হয়েছে');
    }

    // Usage-Record রাখা (Duplicate আটকানোর জন্য)
    $usageStmt = $conn->prepare("INSERT INTO promo_code_usage (code, user_id, bonus_amount) VALUES (?, ?, ?)");
    $usageStmt->bind_param("ssd", $promoCode, $userId, $bonusAmount);
    $usageStmt->execute();

    // Used-Count বাড়ানো
    $conn->query("UPDATE promo_codes SET used_count = used_count + 1 WHERE id = " . (int)$promo['id']);

    $conn->commit();
    echo json_encode(['code' => 0, 'msg' => "সফল! ৳$bonusAmount তোমার Balance-এ যোগ হয়েছে", 'bonus' => $bonusAmount]);

} catch (Throwable $e) {
    $conn->rollback();
    echo json_encode(['code' => 1, 'msg' => 'একটা সমস্যা হয়েছে, আবার চেষ্টা করো']);
}
