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

$formname = 'CHA';
$maindb   = 'accmast';
$mgrpcode = '044';

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

// ── Filters ───────────────────────────────────────────────────────────────
$fname    = isset($_GET['fname'])    ? mysqli_real_escape_string($conn, trim($_GET['fname']))    : '';
$fmobile  = isset($_GET['fmobile'])  ? mysqli_real_escape_string($conn, trim($_GET['fmobile']))  : '';
$faddress = isset($_GET['faddress']) ? mysqli_real_escape_string($conn, trim($_GET['faddress'])) : '';
$fstate   = isset($_GET['fstate'])   ? mysqli_real_escape_string($conn, trim($_GET['fstate']))   : '';
$fgstno   = isset($_GET['fgstno'])   ? mysqli_real_escape_string($conn, trim($_GET['fgstno']))   : '';

$where = "WHERE `grpcode`='$mgrpcode' AND `accode`>50";
if ($fname    != '') $where .= " AND `name` LIKE '%$fname%'";
if ($fmobile  != '') $where .= " AND (`mobile` LIKE '%$fmobile%' OR `mobile2` LIKE '%$fmobile%')";
if ($faddress != '') $where .= " AND (`add1` LIKE '%$faddress%' OR `add2` LIKE '%$faddress%' OR `add3` LIKE '%$faddress%' OR `city` LIKE '%$faddress%')";
if ($fstate   != '') $where .= " AND `state` LIKE '%$fstate%'";
if ($fgstno   != '') $where .= " AND `gstno` LIKE '%$fgstno%'";

$result = mysqli_query($conn, "SELECT * FROM `$maindb` $where ORDER BY `name`") or die(mysqli_error($conn));

// State list for filter dropdown
$stateList = mysqli_query($conn, "SELECT `code`,`name` FROM `state` 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>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.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.4fr 1fr 1.4fr 1.4fr 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); }

        .select2-container .select2-selection--single {
            height:34px;
            border:1px solid #e2e8f0;
            border-radius:6px;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height:32px;
            font-size:12.5px;
            color:#1e293b;
            padding-left:11px;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow { height:32px; }

        .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; }

        .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>Mobile</label>
                <input type="text" name="fmobile" class="finp" placeholder="Mobile no."
                    value="<?php echo htmlspecialchars($fmobile); ?>">
            </div>
            <div>
                <label>Address</label>
                <input type="text" name="faddress" class="finp" placeholder="Address / City"
                    value="<?php echo htmlspecialchars($faddress); ?>">
            </div>
            <div>
                <label>State</label>
                <select name="fstate" class="finp select2" style="width:100%;">
                    <option value="">-- All States --</option>
                    <?php
                    mysqli_data_seek($stateList, 0);
                    while ($srow = mysqli_fetch_assoc($stateList)):
                    ?>
                    <option value="<?php echo htmlspecialchars($srow['name']); ?>"
                        <?php echo ($fstate == $srow['name']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($srow['name']); ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div>
                <label>GST No.</label>
                <input type="text" name="fgstno" class="finp" placeholder="GST No."
                    value="<?php echo htmlspecialchars($fgstno); ?>">
            </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>Name</th>
                    <th>Address</th>
                    <th>Mobile</th>
                    <th>State</th>
                    <th>GST No.</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $count = 0;
                while ($row = mysqli_fetch_array($result)):
                    $count++;
                    $addrParts = array_filter([$row['add1'] ?? '', $row['add2'] ?? '', $row['add3'] ?? '', $row['city'] ?? '', $row['pin'] ?? '']);
                    $address   = implode(', ', $addrParts);
                ?>
                <tr>
                    <td style="font-weight:600;"><?php echo htmlspecialchars($row['name']); ?></td>
                    <td><?php echo $address != '' ? htmlspecialchars($address) : '<span class="muted">—</span>'; ?></td>
                    <td><?php echo htmlspecialchars($row['mobile'] ?? '') ?: '<span class="muted">—</span>'; ?></td>
                    <td><?php echo htmlspecialchars($row['state'] ?? '') ?: '<span class="muted">—</span>'; ?></td>
                    <td><?php echo htmlspecialchars($row['gstno'] ?? '') ?: '<span class="muted">—</span>'; ?></td>
                </tr>
                <?php endwhile; ?>
                <?php if ($count == 0): ?>
                <tr><td colspan="5" style="text-align:center;padding:24px;color:#94a3b8;">No records found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

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

</div>

<script>
$(document).ready(function () {
    $('.select2').select2({ width: '100%' });
});
</script>

</body>
</html>
