<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php"); exit();
}
include('../../includes/config.php');
include('../../includes/header.php');

$store_id   = $_GET['store_id'] ?? '';
$date_from  = $_GET['date_from'] ?? date('Y-m-01');
$date_to    = $_GET['date_to']   ?? date('Y-m-d');
$export     = $_GET['export'] ?? '';

$where = ['DATE(st.created_at)>=?', 'DATE(st.created_at)<=?'];
$params = [$date_from, $date_to];
$types = 'ss';
if ($store_id !== '') {
    $where[] = 'st.store_id=?';
    $params[] = $store_id;
    $types .= 'i';
}

$sql = "SELECT DATE(st.created_at) AS day,
               COUNT(*) AS txns,
               SUM(st.total_amount) AS total,
               AVG(st.total_amount) AS avg
        FROM sales_transactions st
        WHERE ".implode(' AND ',$where)."
        GROUP BY day
        ORDER BY day";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$stores = $conn->query("SELECT id, store_name FROM stores");

if ($export==='excel') {
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=daily_store_report.xls");
    echo "<table border=1><tr><th>Date</th><th>Transactions</th><th>Total Sales</th><th>Avg Sale</th></tr>";
    foreach ($data as $r) {
        echo "<tr><td>{$r['day']}</td><td>{$r['txns']}</td><td>{$r['total']}</td><td>{$r['avg']}</td></tr>";
    }
    echo "</table>"; exit();
}
?>
<!DOCTYPE html><html><head><title>Daily Store Performance</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body{background:fixed url('../../images/profile.jpg') no-repeat center; font-family:'Segoe UI',sans-serif;color:white;}
.overlay{position:fixed;inset:0;background:rgba(0,0,0,0.6);z-index:-1;}
.content{margin:80px auto;max-width:1000px;padding:25px;background:rgba(255,255,255,0.08);backdrop-filter:blur(15px);border-radius:15px;}
.filters{display:flex;gap:10px;margin-bottom:20px;}
.filters select,input,button{padding:8px 10px;border:none;border-radius:6px;background:rgba(255,255,255,0.2);color:white;cursor:pointer;}
.export-btn{background:#ff6f00;}
.summary{display:flex;gap:15px;margin-bottom:20px;}
.summary div{flex:1;background:rgba(255,255,255,0.08);padding:15px;border-radius:8px;text-align:center;}
.summary strong{color:#ffa500;font-size:1.2em;}
table,th,td{border-collapse:collapse;width:100%;background:rgba(0,0,0,0.3);border:1px solid rgba(255,255,255,0.1);padding:10px;}
th{background:#ff6f00;}
     .back-link {
    display: inline-block;
    margin-bottom: 20px;
    padding: 10px 20px;
    background:rgba(255, 111, 0, 0);
    color: white;
    font-weight: 600;
    border-radius: 8px;
    text-decoration: none;
    transition: background-color 0.3s ease;
}
.back-link:hover {
    background: #e65c00;
}

</style>
</head><body><div class="overlay"></div><div class="content">
          <a href="reports.php" class="back-link">&larr; Back to Reports</a>

<h2>Daily Store Performance</h2>
<form class="filters" method="GET">
<select name="store_id"><option value="">All Stores</option>
<?php while($s=$stores->fetch_assoc()): ?>
  <option value="<?=$s['id']?>" <?=($store_id==$s['id']?'selected':'')?>><?=htmlspecialchars($s['store_name'])?></option>
<?php endwhile;?>
</select>
<input type="date" name="date_from" value="<?=$date_from?>"><input type="date" name="date_to" value="<?=$date_to?>">
<button type="submit">Filter</button>
<button type="button" class="export-btn" id="btnExcel">Export Excel</button>
<button type="button" class="export-btn" onclick="window.print()">Export PDF</button>
</form>

<div class="summary">
 <div><strong><?=count($data)?></strong> Days</div>
 <div><strong><?=array_sum(array_column($data,'total'))?></strong> Total Sales</div>
 <div><strong><?=number_format(end($data)['avg'] ?? 0,2)?></strong> Last Day Avg</div>
</div>

<canvas id="chart" height="100"></canvas>

<table><thead><tr><th>Date</th><th>Transactions</th><th>Total Sales</th><th>Avg Sale</th></tr></thead><tbody>
<?php foreach($data as $r): ?>
<tr><td><?=htmlspecialchars($r['day'])?></td><td><?=$r['txns']?></td><td><?=number_format($r['total'],2)?></td><td><?=number_format($r['avg'],2)?></td></tr>
<?php endforeach;?>
</tbody></table>
</div>

<script>
document.getElementById('btnExcel').onclick = ()=>{
  const url = new URL(location);
  url.searchParams.set('export','excel');
  location = url;
};
const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
  type:'bar',
  data:{
    labels: <?=json_encode(array_column($data,'day'))?>,
    datasets:[
      {label:'Total Sales',data:<?=json_encode(array_column($data,'total'))?>,backgroundColor:'rgba(255,111,0,0.6)'},
      {label:'Transactions',data:<?=json_encode(array_column($data,'txns'))?>,backgroundColor:'rgba(0,150,136,0.6)'}
    ]
  },
  options:{responsive:true,scales:{y:{beginAtZero:true}}}
});
</script>
</body></html>
