<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

date_default_timezone_set("Asia/Baghdad");

require_once __DIR__ . "/includes/functions.php";
require_once __DIR__ . "/includes/auth.php";
ensure_manager();

/* ================= LANGUAGE ================= */
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
$_SESSION['lang'] = $lang;
include __DIR__ . "/lang/$lang.php";

function t($k){
    global $tr;
    return $tr[$k] ?? $k;
}

/* ================= DATA ================= */
$restaurant_id = $_SESSION["restaurant_id"];
$items     = get_items($restaurant_id);
$branches  = get_branches($restaurant_id);
$discounts = get_discounts($restaurant_id);


/* ================= TOGGLE (يدوي) ================= */
if (isset($_GET['toggle'])) {

    $id = intval($_GET['toggle']);

    // جلب الحالة الحالية
    $d = fetch_one(
        "SELECT manual_disabled FROM discounts WHERE id=?",
        [$id]
    );

    if ($d && $d['manual_disabled'] == 1) {

        // ✅ تفعيل يدوي
        db()->prepare("
            UPDATE discounts
            SET manual_disabled = 0,
                active = 1
            WHERE id = ?
        ")->execute([$id]);

    } else {

        // ⛔ إيقاف يدوي
        db()->prepare("
            UPDATE discounts
            SET manual_disabled = 1,
                active = 0
            WHERE id = ?
        ")->execute([$id]);
    }

    header("Location: discounts.php");
    exit;
}



/* =================================================
   AUTO UPDATE (DATE + TIME) – يحترم الإيقاف اليدوي
   ================================================= */

/* تفعيل تلقائي */
db()->prepare("
UPDATE discounts
SET active = 1
WHERE restaurant_id = ?
AND manual_disabled = 0
AND CURDATE() BETWEEN DATE(start_date) AND DATE(end_date)
AND CURTIME() BETWEEN daily_start_time AND daily_end_time
")->execute([$restaurant_id]);

/* إيقاف تلقائي خارج الوقت */
if (isset($_GET['toggle'])) {

    $id = intval($_GET['toggle']);

    // جلب الحالة الحالية
    $d = fetch_one(
        "SELECT manual_disabled FROM discounts WHERE id=?",
        [$id]
    );

    if ($d && $d['manual_disabled'] == 1) {

        // تفعيل يدوي (إلغاء الإيقاف)
        db()->prepare("
            UPDATE discounts
            SET manual_disabled = 0
            WHERE id = ?
        ")->execute([$id]);

    } else {

        // إيقاف يدوي
        db()->prepare("
            UPDATE discounts
            SET manual_disabled = 1,
                active = 0
            WHERE id = ?
        ")->execute([$id]);
    }

    header("Location: discounts.php");
    exit;
}

/* ================= ADD DISCOUNT ================= */
if (isset($_POST['add_discount'])) {

    $item_id   = intval($_POST['item_id']);
    $branch_id = $_POST['branch_id'] === 'all' ? null : intval($_POST['branch_id']);
    $type      = clean($_POST['type']);
    $value     = floatval($_POST['value']);

    // تاريخ فقط
    $start = clean($_POST['start_date']); // YYYY-MM-DD
    $end   = clean($_POST['end_date']);   // YYYY-MM-DD

    // ساعة فقط
    $d_start = clean($_POST['daily_start_time']); // HH:MM
    $d_end   = clean($_POST['daily_end_time']);   // HH:MM

    db()->prepare("
        INSERT INTO discounts
        (restaurant_id, item_id, branch_id, discount_type, discount_value,
         start_date, end_date, daily_start_time, daily_end_time,
         active, manual_disabled, created_at)
        VALUES (?,?,?,?,?,?,?,?,?,1,0,NOW())
    ")->execute([
        $restaurant_id,
        $item_id,
        $branch_id,
        $type,
        $value,
        $start,
        $end,
        $d_start,
        $d_end
    ]);

   header("Location: discounts.php?refresh=" . time());
exit;

}



/* ================= DELETE ================= */
if (isset($_GET['delete'])) {
    db()->prepare("DELETE FROM discounts WHERE id=?")
      ->execute([intval($_GET['delete'])]);
    header("Location: discounts.php");
    exit;
}

include __DIR__ . "/includes/header.php";
?>

<div class="content">

<h2 class="page-title"><?= t('discount_system') ?></h2>

<?php if(isset($_GET['added'])): ?>
<div class="msg success"><?= t('discount_added') ?></div>
<?php endif; ?>

<!-- ================= ADD FORM ================= -->
<div class="card">
<h3><?= t('add_discount') ?></h3>

<form method="post">

<div class="grid-2">
<div>
<label><?= t('item') ?></label>
<select name="item_id" required>
<option disabled selected>--</option>
<?php foreach($items as $i): ?>
<option value="<?= $i['id'] ?>"><?= $i['name_'.$lang] ?? $i['name_ar'] ?></option>
<?php endforeach; ?>
</select>
</div>

<div>
<label><?= t('branch') ?></label>
<select name="branch_id">
<option value="all"><?= t('all_branches') ?></option>
<?php foreach($branches as $b): ?>
<option value="<?= $b['id'] ?>"><?= $b['name_'.$lang] ?? $b['name_ar'] ?></option>
<?php endforeach; ?>
</select>
</div>
</div>

<div class="grid-2">
<div>
<label><?= t('discount_type') ?></label>
<select name="type">
<option value="percent">%</option>
<option value="amount">IQD</option>
</select>
</div>

<div>
<label><?= t('discount_value') ?></label>
<input type="number" step="0.01" name="value" required>
</div>
</div>

<div class="grid-2">
<div>
<label><?= t('start_date') ?></label>
<input type="date" name="start_date" required>
</div>
<div>
<label><?= t('end_date') ?></label>
<input type="date" name="end_date" required>
</div>
</div>

<div class="grid-2">
<div>
<label><?= t('daily_start') ?></label>
<input type="time" name="daily_start_time" required>
</div>
<div>
<label><?= t('daily_end') ?></label>
<input type="time" name="daily_end_time" required>
</div>
</div>

<button class="save-btn" name="add_discount"><?= t('add_discount') ?></button>
</form>
</div>

<!-- ================= LIST ================= -->
<div class="discounts-grid">

<?php
$today = date('Y-m-d');
$now   = date('H:i:s');

foreach($discounts as $d):

$item   = get_item($d['item_id']);
$branch = $d['branch_id'] ? get_branch($d['branch_id']) : null;

/* ===== تحديد الحالة ===== */
if ($d['manual_disabled']) {
    $state = 'paused';
} elseif ($today < $d['start_date']) {
    $state = 'upcoming';
} elseif ($today > $d['end_date']) {
    $state = 'ended';
} elseif (
    $now >= $d['daily_start_time'] &&
    $now <= $d['daily_end_time'] &&
    $d['active']
) {
    $state = 'active';
} else {
    $state = 'paused';
}

?>

<div class="discount-card <?= $state ?>">

<div class="disc-title"><?= $item['name_'.$lang] ?? $item['name_ar'] ?></div>
<div class="disc-branch"><?= $branch ? ($branch['name_'.$lang] ?? $branch['name_ar']) : t('all_branches') ?></div>

<div class="disc-body">
<div class="disc-value">
<?= $d['discount_type']=='percent'
? $d['discount_value'].'%'
: number_format($d['discount_value'],0).' IQD' ?>
</div>

<div class="disc-date">
<?= date('Y-m-d', strtotime($d['start_date'])) ?>
 →
<?= date('Y-m-d', strtotime($d['end_date'])) ?><br>
<?= $d['daily_start_time'] ?> - <?= $d['daily_end_time'] ?>
</div>
</div>

<div class="disc-footer">
<a class="btn-sm" href="?toggle=<?= $d['id'] ?>">
<?= $state === 'paused' ? t('activate') : t('deactivate') ?>
</a>
<a class="btn-delete" href="?delete=<?= $d['id'] ?>" onclick="return confirm('OK?')">
<?= t('delete') ?>
</a>
</div>

</div>
<?php endforeach; ?>

</div>
</div>

<style>
.card{background:#1c1c1c;padding:20px;border-radius:12px;border:1px solid #333;margin-bottom:25px}
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:15px}
select,input{width:100%;padding:10px;background:#111;color:#fff;border-radius:8px;border:1px solid #444}
.save-btn{margin-top:15px;width:100%;padding:12px;background:#ff7a00;border:none;border-radius:10px;font-weight:bold}

.discounts-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:18px}
.discount-card{background:#1b1b1b;padding:15px;border-radius:12px;border:1px solid transparent}

.discount-card.active{border-color:#00ff80}
.discount-card.upcoming{border-color:#ffffff}
.discount-card.ended{opacity:.5}
.discount-card.paused{border-color:#666}

.disc-footer{display:flex;justify-content:space-between;margin-top:10px}
.btn-sm{background:#ffbb00;padding:6px 10px;border-radius:6px;color:#000;text-decoration:none}
.btn-delete{background:#d82626;padding:6px 10px;border-radius:6px;color:#fff;text-decoration:none}
.discount-card{
    background:#1b1b1b;
    padding:15px;
    border-radius:12px;
    border:1px solid transparent;
}

/* فعال الآن */
.discount-card.active{
    border:2px solid #00ff80; /* أخضر */
}

/* لم يبدأ بعد */
.discount-card.upcoming{
    border:2px solid #ffffff; /* أبيض */
}

/* منتهي */
.discount-card.ended{
    border:none;              /* بدون إطار */
    opacity:0.6;
}

/* موقوف يدويًا أو خارج الوقت */
.discount-card.paused{
    border:1px solid #666;    /* رمادي */
}

</style>
