<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");

$formname = 'Product';
$maindb   = 'product';

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

// ── Filters ───────────────────────────────────────────────────────────────
$fname     = isset($_GET['fname'])     ? mysqli_real_escape_string($conn, trim($_GET['fname']))     : '';
$funit     = isset($_GET['funit'])     ? mysqli_real_escape_string($conn, trim($_GET['funit']))     : '';
$fcostmin  = isset($_GET['fcostmin'])  ? mysqli_real_escape_string($conn, trim($_GET['fcostmin']))  : '';
$fcostmax  = isset($_GET['fcostmax'])  ? mysqli_real_escape_string($conn, trim($_GET['fcostmax']))  : '';
$famtmin   = isset($_GET['famtmin'])   ? mysqli_real_escape_string($conn, trim($_GET['famtmin']))   : '';
$famtmax   = isset($_GET['famtmax'])   ? mysqli_real_escape_string($conn, trim($_GET['famtmax']))   : '';

$allowedSort = ['id', 'name', 'cost', 'amount', 'unit', 'unitpercarton'];
$fsort  = isset($_GET['fsort'])  && in_array($_GET['fsort'], $allowedSort) ? $_GET['fsort'] : 'name';
$forder = isset($_GET['forder']) && strtoupper($_GET['forder']) == 'DESC' ? 'DESC' : 'ASC';

$where = [];
if ($fname    != '') $where[] = "`name` LIKE '%$fname%'";
if ($funit    != '') $where[] = "`unit`='$funit'";
if ($fcostmin != '') $where[] = "`cost` >= '$fcostmin'";
if ($fcostmax != '') $where[] = "`cost` <= '$fcostmax'";
if ($famtmin  != '') $where[] = "`amount` >= '$famtmin'";
if ($famtmax  != '') $where[] = "`amount` <= '$famtmax'";

$sql = "SELECT * FROM `$maindb`";
if (count($where) > 0) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " ORDER BY `$fsort` $forder";

$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));

// Unit list for filter dropdown
$unitList = mysqli_query($conn, "SELECT `code`,`name` FROM `unit` ORDER BY `name`") or die(mysqli_error($conn));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $formname; ?> List</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body { background:#f0f2f5; margin:0; padding:14px; font-family: ui-sans-serif, system-ui, sans-serif; }

        .sim-card {
            background:#fff;
            border-radius:10px;
            box-shadow:0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06);
            overflow:hidden;
        }
        .sim-card-header {
            background:#fff;
            border-bottom:2px solid #f1f5f9;
            padding:12px 20px;
            display:flex;
            align-items:center;
            justify-content:space-between;
        }
        .sim-card-header h2 {
            font-size:15px;
            font-weight:700;
            color:#1e293b;
            margin:0;
            letter-spacing:.01em;
        }

        /* Filter bar */
        .filter-bar {
            padding:14px 20px;
            border-bottom:1px solid #f1f5f9;
            display:grid;
            grid-template-columns: 1.6fr 1fr 1fr 1fr 1fr 1fr 1fr auto;
            gap:10px;
            align-items:end;
            background:#fafbfc;
        }
        .filter-bar label {
            font-size:10.5px;
            font-weight:700;
            text-transform:uppercase;
            letter-spacing:.06em;
            color:#94a3b8;
            display:block;
            margin-bottom:4px;
        }
        .finp {
            width:100%;
            padding:7px 11px;
            background:#fff;
            border:1px solid #e2e8f0;
            border-radius:6px;
            font-size:12.5px;
            color:#1e293b;
            outline:none;
            box-sizing:border-box;
            font-family:inherit;
        }
        .finp:focus { border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }

        .fbtn {
            padding:8px 16px;
            border-radius:6px;
            border:none;
            font-size:12.5px;
            font-weight:600;
            cursor:pointer;
            color:#fff;
            display:inline-flex;
            align-items:center;
            gap:6px;
            white-space:nowrap;
        }
        .fbtn-go    { background:#2563eb; }
        .fbtn-clear { background:#64748b; }
        .fbtn-print { background:#7c3aed; }

        .action-bar {
            display:flex; justify-content:flex-end; gap:8px; padding:0 20px 14px;
        }

        table { width:100%; border-collapse:collapse; font-size:12px; }
        thead th {
            position:sticky; top:0; background:#f8fafc;
            padding:9px 14px; text-align:left;
            border-bottom:2px solid #e2e8f0;
            font-weight:600; color:#374151; font-size:11.5px;
            text-transform:uppercase; letter-spacing:.04em;
        }
        tbody td {
            padding:8px 14px; border-bottom:1px solid #f1f5f9; color:#1e293b;
        }
        tbody tr:nth-child(even) td { background:#f8fafc; }
        .muted { color:#94a3b8; }
        .num { text-align:right; }

        .summary { padding:10px 20px; font-size:11.5px; color:#64748b; border-top:1px solid #f1f5f9; }

        @media print {
            body { background:#fff; padding:0; }
            .filter-bar, .action-bar { display:none !important; }
            .sim-card { box-shadow:none; border-radius:0; }
            .sim-card-header { border-bottom:2px solid #000; }
            thead th { background:#fff !important; }
            tbody tr:nth-child(even) td { background:#fff !important; }
        }
    </style>
</head>
<body>

<div class="sim-card">

    <div class="sim-card-header">
        <h2><i class="fa fa-list" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?> List</h2>
        <span style="font-size:11px;color:#94a3b8;"><?php echo date('d-M-Y'); ?></span>
    </div>

    <form method="GET" action="">
        <div class="filter-bar">
            <div>
                <label>Name</label>
                <input type="text" name="fname" class="finp" placeholder="Search by name"
                    value="<?php echo htmlspecialchars($fname); ?>">
            </div>
            <div>
                <label>Unit</label>
                <select name="funit" class="finp">
                    <option value="">-- All Units --</option>
                    <?php while ($urow = mysqli_fetch_assoc($unitList)): ?>
                    <option value="<?php echo htmlspecialchars($urow['name']); ?>"
                        <?php echo ($funit == $urow['name']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($urow['name']); ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div>
                <label>Cost (Min)</label>
                <input type="number" step="0.01" name="fcostmin" class="finp"
                    value="<?php echo htmlspecialchars($fcostmin); ?>">
            </div>
            <div>
                <label>Cost (Max)</label>
                <input type="number" step="0.01" name="fcostmax" class="finp"
                    value="<?php echo htmlspecialchars($fcostmax); ?>">
            </div>
            <div>
                <label>Amount (Min)</label>
                <input type="number" step="0.01" name="famtmin" class="finp"
                    value="<?php echo htmlspecialchars($famtmin); ?>">
            </div>
            <div>
                <label>Amount (Max)</label>
                <input type="number" step="0.01" name="famtmax" class="finp"
                    value="<?php echo htmlspecialchars($famtmax); ?>">
            </div>
            <div>
                <label>Sort By</label>
                <select name="fsort" class="finp">
                    <option value="name"          <?php echo ($fsort=='name')          ? 'selected' : ''; ?>>Name</option>
                    <option value="id"            <?php echo ($fsort=='id')            ? 'selected' : ''; ?>>ID</option>
                    <option value="cost"          <?php echo ($fsort=='cost')          ? 'selected' : ''; ?>>Cost</option>
                    <option value="amount"        <?php echo ($fsort=='amount')        ? 'selected' : ''; ?>>Amount</option>
                    <option value="unit"          <?php echo ($fsort=='unit')          ? 'selected' : ''; ?>>Unit</option>
                    <option value="unitpercarton" <?php echo ($fsort=='unitpercarton') ? 'selected' : ''; ?>>Pcs/Unit</option>
                </select>
            </div>
            <div style="display:flex; gap:8px;">
                <button type="submit" class="fbtn fbtn-go"><i class="fa fa-filter"></i> Filter</button>
                <a href="<?php echo basename($_SERVER['PHP_SELF']); ?>" class="fbtn fbtn-clear"><i class="fa fa-times"></i></a>
            </div>
        </div>
    </form>

    <div class="action-bar">
        <button type="button" class="fbtn fbtn-print" onclick="window.print()"><i class="fa fa-print"></i> Print</button>
    </div>

    <div style="overflow:auto;">
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Unit</th>
                    <th class="num">Pcs/Unit</th>
                    <th class="num">Cost</th>
                    <th class="num">Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $count    = 0;
                $totcost  = 0;
                $totamt   = 0;
                while ($row = mysqli_fetch_array($result)):
                    $count++;
                    $totcost += (float)$row['cost'];
                    $totamt  += (float)$row['amount'];
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['id']); ?></td>
                    <td>
                        <?php if ($row['image'] != ''): ?>
                        <img src="uploads/products/<?php echo htmlspecialchars($row['image']); ?>" alt=""
                            style="width:40px;height:40px;object-fit:cover;border:1px solid #e2e8f0;border-radius:4px;">
                        <?php else: ?>
                        <span class="muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td style="font-weight:600;"><?php echo htmlspecialchars($row['name']); ?></td>
                    <td><?php echo $row['unit'] != '' ? htmlspecialchars($row['unit']) : '<span class="muted">—</span>'; ?></td>
                    <td class="num"><?php echo number_format((float)$row['unitpercarton'], 2); ?></td>
                    <td class="num"><?php echo number_format((float)$row['cost'], 2); ?></td>
                    <td class="num"><?php echo number_format((float)$row['amount'], 2); ?></td>
                </tr>
                <?php endwhile; ?>
                <?php if ($count == 0): ?>
                <tr><td colspan="7" style="text-align:center;padding:24px;color:#94a3b8;">No records found.</td></tr>
                <?php else: ?>
                <tr style="font-weight:700;background:#f8fafc;">
                    <td colspan="5" style="text-align:right;">Total</td>
                    <td class="num"><?php echo number_format($totcost, 2); ?></td>
                    <td class="num"><?php echo number_format($totamt, 2); ?></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <div class="summary">Total Records: <?php echo $count; ?></div>

</div>

</body>
</html>
