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

/* ================= LANGUAGE ================= */
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
$_SESSION['lang'] = $lang;
include __DIR__ . "/lang/$lang.php";
function t($k){ global $tr; return $tr[$k] ?? $k; }

$page_title = t('reports_title');
require_once "includes/header.php";

/* ============================
    فلاتر التقرير (كما هي)
============================ */
$filter_branch = $_GET['branch'] ?? 'all';
$filter_type   = $_GET['type']   ?? 'all';  // all | month | day
$filter_value  = $_GET['date']   ?? null;

$where  = " v.restaurant_id = ? ";
$params = [$restaurant_id];

/* فلتر الفرع */
if ($filter_branch !== "all") {
    $where  .= " AND v.branch_id = ? ";
    $params[] = $filter_branch;
}

/* فلتر التاريخ */
if ($filter_type === "month" && $filter_value) {
    $where .= " AND DATE_FORMAT(v.created_at,'%Y-%m') = ? ";
    $params[] = $filter_value;
}
elseif ($filter_type === "day" && $filter_value) {
    $where .= " AND DATE(v.created_at) = ? ";
    $params[] = $filter_value;
}

/* ============================
    الاستعلامات (كما هي)
============================ */
$total_visits = fetch_value("SELECT COUNT(*) FROM visits v WHERE $where", $params);

$today_visits = fetch_value("
    SELECT COUNT(*) FROM visits v
    WHERE $where AND DATE(v.created_at)=CURDATE()
", $params);

$branches_report = fetch_all("
    SELECT b.name_$lang AS branch, COUNT(v.id) AS total
    FROM visits v 
    JOIN branches b ON v.branch_id = b.id
    WHERE $where
    GROUP BY v.branch_id
    ORDER BY total DESC
", $params);

$items_report = fetch_all("
    SELECT i.name_$lang AS item, COUNT(v.id) AS total
    FROM visits v 
    JOIN items i ON v.item_id = i.id
    WHERE $where AND v.item_id IS NOT NULL
    GROUP BY v.item_id
    ORDER BY total DESC
", $params);

/* تقرير فترات حسب الفلتر (كما هو) */
$range_report = fetch_all("
    SELECT DATE_FORMAT(v.created_at, '%Y-%m-%d') AS day, COUNT(*) AS total
    FROM visits v
    WHERE $where
    GROUP BY day
    ORDER BY day DESC
    LIMIT 31
", $params);

/* جلب فروع المطعم (كما هو) */
$branches = get_branches($restaurant_id);

/* =====================================================
   ============ إضافات الإعجابات (item_likes) ============
   ===================================================== */

/* إجمالي الإعجابات */
$total_likes = fetch_value("
    SELECT COUNT(*)
    FROM item_likes l
    JOIN items i ON l.item_id = i.id
    WHERE i.restaurant_id = ?
", [$restaurant_id]);

/* إعجابات اليوم */
$today_likes = fetch_value("
    SELECT COUNT(*)
    FROM item_likes l
    JOIN items i ON l.item_id = i.id
    WHERE i.restaurant_id = ?
    AND DATE(l.created_at)=CURDATE()
", [$restaurant_id]);

/* ترتيب الأصناف حسب الإعجاب */
$likes_items = fetch_all("
    SELECT i.name_$lang AS item, COUNT(l.id) AS total
    FROM item_likes l
    JOIN items i ON l.item_id = i.id
    WHERE i.restaurant_id = ?
    GROUP BY l.item_id
    ORDER BY total DESC
", [$restaurant_id]);

/* تفاصيل الإعجابات */
$likes_details = fetch_all("
    SELECT 
        i.name_$lang AS item,
        b.name_$lang AS branch,
        l.ip,
        l.created_at
    FROM item_likes l
    JOIN items i ON l.item_id = i.id
    LEFT JOIN branches b ON l.branch_id = b.id
    WHERE i.restaurant_id = ?
    ORDER BY l.created_at DESC
    LIMIT 100
", [$restaurant_id]);
?>

<style>
h1{margin-top:0;font-size:28px;}
.cards{display:grid;grid-template-columns:repeat(4,1fr);gap:20px;margin-bottom:30px;}
.card{background:#1c1c1c;padding:22px;border-radius:12px;border:1px solid #333;}
.card h3{margin:0;font-size:18px;color:#ccc;}
.card .num{font-size:34px;color:#ff7a00;margin-top:10px;font-weight:bold;}

.table-box{background:#1c1c1c;padding:20px;border-radius:14px;border:1px solid #333;margin-top:30px;}
table{width:100%;border-collapse:collapse;}
th,td{padding:12px;border-bottom:1px solid #333;}
th{background:#222;color:#ff7a00;font-size:15px;text-align:right;}

.filter-box{
    background:#1c1c1c;padding:15px;border-radius:12px;border:1px solid #333;margin-bottom:25px;
}
.filter-box label{display:block;margin-bottom:6px;color:#ccc;font-size:14px;}
.filter-box select, .filter-box input{
    width:100%;padding:10px;background:#111;border:1px solid #333;border-radius:8px;color:#fff;margin-bottom:10px;
}
.filter-box button{
    background:#ff7a00;padding:10px 18px;border:none;border-radius:8px;color:#000;font-weight:bold;cursor:pointer;
}
.filter-box button:hover{background:#e06b00;}
</style>

<h1>📊 <?= t('reports_title') ?></h1>

<!-- فلاتر (كما هي) -->
<div class="filter-box">
<form method="GET">
    <label><?= t('branch') ?></label>
    <select name="branch">
        <option value="all"><?= t('all_branches') ?></option>
        <?php foreach($branches as $b): ?>
            <option value="<?= $b['id'] ?>" <?= ($filter_branch==$b['id']?'selected':'') ?>>
                <?= $b['name_'.$lang] ?>
            </option>
        <?php endforeach; ?>
    </select>

    <label><?= t('date_type') ?></label>
    <select name="type" id="type" onchange="changeType()">
        <option value="all"   <?= $filter_type=='all'?'selected':'' ?>><?= t('all_time') ?></option>
        <option value="month" <?= $filter_type=='month'?'selected':'' ?>><?= t('by_month') ?></option>
        <option value="day"   <?= $filter_type=='day'?'selected':'' ?>><?= t('by_day') ?></option>
    </select>

    <label><?= t('choose_date') ?></label>
    <input type="month" name="date" id="month" style="display:<?= $filter_type=='month'?'block':'none' ?>;">
    <input type="date" name="date" id="day" style="display:<?= $filter_type=='day'?'block':'none' ?>;">

    <button type="submit">🔎 <?= t('apply') ?></button>
</form>
</div>

<script>
function changeType(){
    let type = document.getElementById("type").value;
    document.getElementById("month").style.display = (type === "month") ? "block" : "none";
    document.getElementById("day").style.display   = (type === "day") ? "block" : "none";
}
</script>

<!-- الكروت (كما هي) -->
<div class="cards">
    <div class="card"><h3><?= t('total_visits') ?></h3><div class="num"><?= $total_visits ?></div></div>
    <div class="card"><h3><?= t('today_visits') ?></h3><div class="num"><?= $today_visits ?></div></div>
    <div class="card"><h3><?= t('top_branch') ?></h3><div class="num"><?= $branches_report[0]['total'] ?? 0 ?></div></div>
    <div class="card"><h3><?= t('top_item') ?></h3><div class="num"><?= $items_report[0]['total'] ?? 0 ?></div></div>
</div>

<!-- الفروع (كما هي) -->
<div class="table-box">
    <h2>📍 <?= t('branches_visits') ?></h2>
    <table>
        <tr><th><?= t('branch') ?></th><th><?= t('visits_count') ?></th></tr>
        <?php foreach($branches_report as $row): ?>
        <tr><td><?= $row['branch'] ?></td><td><?= $row['total'] ?></td></tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- الأصناف الأكثر زيارة (كما هي) -->
<div class="table-box">
    <h2>🍔 <?= t('top_visited_items') ?></h2>
    <table>
        <tr><th><?= t('item') ?></th><th><?= t('visits_count') ?></th><th><?= t('percent') ?></th></tr>
        <?php foreach($items_report as $row):
            $percent = ($total_visits>0)? round(($row['total']/$total_visits)*100,2) : 0; ?>
        <tr><td><?= $row['item'] ?></td><td><?= $row['total'] ?></td><td><?= $percent ?>%</td></tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- تقرير الفترة (كما هو) -->
<div class="table-box">
    <h2>📅 <?= t('range_report') ?></h2>
    <table>
        <tr><th><?= t('date') ?></th><th><?= t('visits_count') ?></th></tr>
        <?php foreach($range_report as $row): ?>
        <tr><td><?= $row['day'] ?></td><td><?= $row['total'] ?></td></tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- ===== إضافات الإعجابات (جديدة فقط) ===== -->
<div class="table-box">
    <h2>❤️ <?= t('top_liked_items') ?></h2>
    <table>
        <tr><th><?= t('item') ?></th><th><?= t('likes_count') ?></th></tr>
        <?php foreach($likes_items as $r): ?>
        <tr><td><?= $r['item'] ?></td><td><?= $r['total'] ?></td></tr>
        <?php endforeach; ?>
    </table>
</div>

<div class="table-box">
    <h2>🕒 <?= t('likes_details') ?></h2>
    <table>
        <tr>
            <th><?= t('item') ?></th>
            <th><?= t('branch') ?></th>
            <th>IP</th>
            <th><?= t('date') ?></th>
        </tr>
        <?php foreach($likes_details as $l): ?>
        <tr>
            <td><?= $l['item'] ?></td>
            <td><?= $l['branch'] ?? '-' ?></td>
            <td><?= $l['ip'] ?></td>
            <td><?= date('Y-m-d H:i',strtotime($l['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<?php require_once "includes/footer.php"; ?>
