<?php
include('session.php');

$where = " WHERE 1 ";

if (!empty($_GET['cc_id'])) {
    $cc_id = (int)$_GET['cc_id'];
    $where .= " AND cl.cc_id = '$cc_id' ";
}

if (!empty($_GET['cs_id'])) {
    $cs_id = (int)$_GET['cs_id'];
    $where .= " AND cl.cs_id = '$cs_id' ";
}

if (!empty($_GET['search'])) {
    $search = $conn->real_escape_string($_GET['search']);
    $where .= " AND (
        cc.name LIKE '%$search%' OR
        cs.name LIKE '%$search%' OR
        cl.nature_comp LIKE '%$search%' OR
        cl.compcode LIKE '%$search%'
    ) ";
}

$sql = "
SELECT 
    cl.na_id,
    cl.nature_comp,
    cl.compcode,
    cc.name AS category_name,
    cs.name AS subcategory_name
FROM complaints_lists cl
LEFT JOIN complaint_category cc ON cc.cc_id = cl.cc_id
LEFT JOIN complaint_subcategory cs ON cs.cs_id = cl.cs_id
$where
ORDER BY cc.name ASC, cs.name ASC, cl.nature_comp ASC
";

if (isset($_GET['export']) && $_GET['export'] == 'csv') {
    $result = $conn->query($sql);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=complaint-list.csv');

    $output = fopen("php://output", "w");

    fputcsv($output, [
        'Sr No.',
        'Category',
        'Sub Category',
        'Complaint Name',
        'Complaint Code'
    ]);

    $i = 1;

    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $i++,
            $row['category_name'],
            $row['subcategory_name'],
            $row['nature_comp'],
            $row['compcode']
        ]);
    }

    fclose($output);
    exit;
}

$complaints = $conn->query($sql);

$categories = $conn->query("
    SELECT cc_id, name 
    FROM complaint_category 
    ORDER BY name ASC
");

$subcategories = $conn->query("
    SELECT cs_id, cc_id, name 
    FROM complaint_subcategory 
    ORDER BY name ASC
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Complaint List</title>
    <?php include('includes/head.php'); ?>

    <style>
        th, td {
            text-align: center;
            vertical-align: middle !important;
        }

        .filter-box {
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            border: 1px solid #ddd;
        }

        .table-card {
            background: #fff;
            border-radius: 10px;
            padding: 20px;
            border: 1px solid #ddd;
        }
    </style>
</head>

<body>
<div class="container-scroller">

    <div class="horizontal-menu">
        <?php include('includes/header.php'); ?>
    </div>

    <div class="container-fluid page-body-wrapper">
        <div class="main-panel">
            <div class="content-wrapper">

                <div class="page-header">
                    <h3 class="page-title">Complaint List</h3>
                </div>

                <div class="filter-box">
                    <form method="GET">
                        <div class="row">

                            <div class="col-md-3">
                                <label>Category</label>
                                <select name="cc_id" class="form-control">
                                    <option value="">All Categories</option>
                                    <?php while ($cat = $categories->fetch_assoc()) { ?>
                                        <option value="<?= $cat['cc_id']; ?>"
                                            <?= (isset($_GET['cc_id']) && $_GET['cc_id'] == $cat['cc_id']) ? 'selected' : ''; ?>>
                                            <?= htmlspecialchars($cat['name']); ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>

                            <div class="col-md-3">
                                <label>Sub Category</label>
                                <select name="cs_id" class="form-control">
                                    <option value="">All Sub Categories</option>
                                    <?php while ($sub = $subcategories->fetch_assoc()) { ?>
                                        <option value="<?= $sub['cs_id']; ?>"
                                            <?= (isset($_GET['cs_id']) && $_GET['cs_id'] == $sub['cs_id']) ? 'selected' : ''; ?>>
                                            <?= htmlspecialchars($sub['name']); ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>

                            <div class="col-md-3">
                                <label>Search</label>
                                <input type="text" 
                                       name="search" 
                                       class="form-control"
                                       placeholder="Search complaint"
                                       value="<?= htmlspecialchars($_GET['search'] ?? ''); ?>">
                            </div>

                            <div class="col-md-3" style="padding-top: 28px;">
                                <button type="submit" class="btn btn-primary">
                                    Filter
                                </button>

                                <a href="complaint-list.php" class="btn btn-secondary">
                                    Reset
                                </a>

                                <?php
$currentPage = basename($_SERVER['PHP_SELF']);
$exportUrl = $currentPage . "?" . http_build_query(array_merge($_GET, ['export' => 'csv']));
?>

<a href="<?= $exportUrl; ?>" class="btn btn-success">
    CSV Export
</a>
                            </div>

                        </div>
                    </form>
                </div>

                <div class="table-card">
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered">
                            <thead>
                                <tr>
                                    <th>Sr No.</th>
                                    <th>Category</th>
                                    <th>Sub Category</th>
                                    <th>Complaint Name</th>
                                    <th>Complaint Code</th>
                                </tr>
                            </thead>

                            <tbody>
                                <?php
                                if ($complaints && $complaints->num_rows > 0) {
                                    $sr = 1;
                                    while ($row = $complaints->fetch_assoc()) {
                                ?>
                                        <tr>
                                            <td><?= $sr++; ?></td>
                                            <td><?= htmlspecialchars($row['category_name']); ?></td>
                                            <td><?= htmlspecialchars($row['subcategory_name']); ?></td>
                                            <td><?= htmlspecialchars($row['nature_comp']); ?></td>
                                            <td><?= htmlspecialchars($row['compcode']); ?></td>
                                        </tr>
                                <?php
                                    }
                                } else {
                                ?>
                                    <tr>
                                        <td colspan="5">No complaint found.</td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </div>

</div>

<?php include('includes/scripts.php'); ?>

</body>
</html>