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

$msg = $err = '';
$editData = null;

/* Delete */
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("UPDATE building_list SET isDeleted='1' WHERE bid='$id'");
    header("Location: building.php?msg=deleted");
    exit;
}

/* Edit */
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $editQ = $conn->query("SELECT * FROM building_list WHERE bid='$id' AND isDeleted='0'");
    if ($editQ && $editQ->num_rows > 0) {
        $editData = $editQ->fetch_assoc();
    }
}

/* Add / Update */
if (isset($_POST['submit'])) {
    $bid = (int)($_POST['bid'] ?? 0);

    $division_id = (int)$_POST['division_id'];
    $department_id = (int)$_POST['department_id'];
    $colony_id = (int)$_POST['colony_id'];

    $bNo = mysqli_real_escape_string($conn, $_POST['bNo']);
    $bcategory = mysqli_real_escape_string($conn, $_POST['bcategory']);
    $bName = mysqli_real_escape_string($conn, $_POST['bName']);
    $landmark = mysqli_real_escape_string($conn, $_POST['landmark']);
    $mpin = mysqli_real_escape_string($conn, $_POST['mpin']);

    if ($bid > 0) {
        $sql = "UPDATE building_list SET 
                    bNo='$bNo',
                    bcategory='$bcategory',
                    bName='$bName',
                    landmark='$landmark',
                    division_id='$division_id',
                    department_id='$department_id',
                    colony_id='$colony_id',
                    mpin='$mpin'
                WHERE bid='$bid'";

        if ($conn->query($sql)) {
            header("Location: building.php?msg=updated");
            exit;
        } else {
            $err = $conn->error;
        }
    } else {
        $sql = "INSERT INTO building_list 
                (bNo, bcategory, bName, landmark, isDeleted, division_id, department_id, colony_id, mpin)
                VALUES 
                ('$bNo', '$bcategory', '$bName', '$landmark', '0', '$division_id', '$department_id', '$colony_id', '$mpin')";

        if ($conn->query($sql)) {
            header("Location: building.php?msg=added");
            exit;
        } else {
            $err = $conn->error;
        }
    }
}

/* Messages */
if (isset($_GET['msg'])) {
    if ($_GET['msg'] == 'added') $msg = 'Building added successfully.';
    if ($_GET['msg'] == 'updated') $msg = 'Building updated successfully.';
    if ($_GET['msg'] == 'deleted') $msg = 'Building deleted successfully.';
}

/* Filter Values */
$filter_division = isset($_GET['filter_division']) ? (int)$_GET['filter_division'] : 0;
$filter_department = isset($_GET['filter_department']) ? (int)$_GET['filter_department'] : 0;
$filter_colony = isset($_GET['filter_colony']) ? (int)$_GET['filter_colony'] : 0;
$filter_category = isset($_GET['filter_category']) ? mysqli_real_escape_string($conn, $_GET['filter_category']) : '';

$where = " WHERE b.isDeleted='0' ";

if ($filter_division > 0) {
    $where .= " AND b.division_id='$filter_division' ";
}

if ($filter_department > 0) {
    $where .= " AND b.department_id='$filter_department' ";
}

if ($filter_colony > 0) {
    $where .= " AND b.colony_id='$filter_colony' ";
}

if ($filter_category != '') {
    $where .= " AND b.bcategory='$filter_category' ";
}

/* Dropdown Data */
$divisions = $conn->query("SELECT id, name FROM divisions ORDER BY name ASC");
$filterDivisions = $conn->query("SELECT id, name FROM divisions ORDER BY name ASC");

$categories = $conn->query("
    SELECT DISTINCT bcategory 
    FROM building_list 
    WHERE isDeleted='0' 
    AND bcategory IS NOT NULL 
    AND bcategory != '' 
    ORDER BY bcategory ASC
");

/* Buildings List */
$buildings = $conn->query("
    SELECT 
        b.*,
        d.name AS division_name,
        dep.name AS department_name,
        c.name AS colony_name
    FROM building_list b
    LEFT JOIN divisions d ON d.id = b.division_id
    LEFT JOIN departments dep ON dep.id = b.department_id
    LEFT JOIN colonies c ON c.id = b.colony_id
    $where
    ORDER BY b.bid DESC
");


/* CSV Export */
if (isset($_GET['export']) && $_GET['export'] == 'csv') {

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

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

    fputcsv($output, array(
        'Sr No',
        'Division',
        'Sub Division',
        'Colony',
        'Building Category',
        'Building No',
        'Building Name',
        'Login Pin',
        'Landmark'
    ));

    $exportQ = $conn->query("
        SELECT 
            b.*,
            d.name AS division_name,
            dep.name AS department_name,
            c.name AS colony_name
        FROM building_list b
        LEFT JOIN divisions d ON d.id = b.division_id
        LEFT JOIN departments dep ON dep.id = b.department_id
        LEFT JOIN colonies c ON c.id = b.colony_id
        $where
        ORDER BY b.bid DESC
    ");

    $sr = 1;

    if ($exportQ && $exportQ->num_rows > 0) {
        while ($row = $exportQ->fetch_assoc()) {
            fputcsv($output, array(
                $sr++,
                $row['division_name'],
                $row['department_name'],
                $row['colony_name'],
                $row['bcategory'],
                $row['bNo'],
                $row['bName'],
                $row['mpin'],
                $row['landmark']
            ));
        }
    }

    fclose($output);
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>ECIMS ADMIN | BUILDINGS</title>
    <?php include('includes/head.php'); ?>

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

        .form-control {
            height: 45px;
        }

        .card-title-custom {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .filter-box {
            background: #f8f9fa;
            padding: 18px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #e5e5e5;
        }
    </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">
                        <?php echo $editData ? 'Edit Building' : 'Add / View Buildings'; ?>
                    </h3>
                </div>

                <?php if (!empty($err)) { ?>
                    <div class="alert alert-danger">
                        <strong>Error!</strong> <?php echo $err; ?>
                    </div>
                <?php } ?>

                <?php if (!empty($msg)) { ?>
                    <div class="alert alert-success">
                        <strong>Success!</strong> <?php echo $msg; ?>
                    </div>
                <?php } ?>

                <!-- Add / Edit Form -->
                <div class="row">
                    <div class="col-12 grid-margin stretch-card">
                        <div class="card">
                            <div class="card-body">

                                <h4 class="card-title-custom">
                                    <?php echo $editData ? 'Update Building' : 'Add New Building'; ?>
                                </h4>

                                <form method="POST" class="forms-sample">

                                    <input type="hidden" name="bid" value="<?php echo $editData['bid'] ?? 0; ?>">

                                    <div class="row">

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Division *</label>
                                                <select name="division_id" id="division_id" class="form-control" required>
                                                    <option value="">Select Division</option>
                                                    <?php while ($div = $divisions->fetch_assoc()) { ?>
                                                        <option value="<?php echo $div['id']; ?>"
                                                            <?php echo (($editData['division_id'] ?? '') == $div['id']) ? 'selected' : ''; ?>>
                                                            <?php echo $div['name']; ?>
                                                        </option>
                                                    <?php } ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Sub Division *</label>
                                                <select name="department_id" id="department_id" class="form-control" required>
                                                    <option value="">Select Sub Division</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Colony / RWA *</label>
                                                <select name="colony_id" id="colony_id" class="form-control" required>
                                                    <option value="">Select Colony</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Building No *</label>
                                                <input type="text" name="bNo" class="form-control" required
                                                       placeholder="Building No"
                                                       value="<?php echo $editData['bNo'] ?? ''; ?>">
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Building Category *</label>
                                                <input type="text" name="bcategory" class="form-control" required
                                                       placeholder="Building Category"
                                                       value="<?php echo $editData['bcategory'] ?? ''; ?>">
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Building Name *</label>
                                                <input type="text" name="bName" class="form-control" required
                                                       placeholder="Building Name"
                                                       value="<?php echo $editData['bName'] ?? ''; ?>">
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Login Pin *</label>
                                                <input type="text" name="mpin" class="form-control" required
                                                       maxlength="4"
                                                       placeholder="Login Pin"
                                                       value="<?php echo $editData['mpin'] ?? ''; ?>">
                                            </div>
                                        </div>

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Landmark *</label>
                                                <input type="text" name="landmark" class="form-control" required
                                                       placeholder="Landmark"
                                                       value="<?php echo $editData['landmark'] ?? ''; ?>">
                                            </div>
                                        </div>

                                    </div>

                                    <button type="submit" name="submit" class="btn btn-primary me-2">
                                        <?php echo $editData ? 'Update Building' : 'Add Building'; ?>
                                    </button>

                                    <?php if ($editData) { ?>
                                        <a href="building.php" class="btn btn-light">Cancel</a>
                                    <?php } ?>

                                </form>

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

                <!-- Building List -->
                <div class="card grid-margin">
                    <div class="card-body">

                        <h4 class="card-title-custom">All Buildings</h4>

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

                                <div class="col-md-3">
                                    <label>Filter By Division </label>
                                    <select name="filter_division" id="filter_division" class="form-control">
                                       
                                        <?php while ($fdiv = $filterDivisions->fetch_assoc()) { ?>
                                            <option value="<?php echo $fdiv['id']; ?>"
                                                <?php echo ($filter_division == $fdiv['id']) ? 'selected' : ''; ?>>
                                                <?php echo $fdiv['name']; ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>

                                <div class="col-md-3">
                                    <label>Filter By Sub Division  </label>
                                    <select name="filter_department" id="filter_department" class="form-control">
                                       
                                    </select>
                                </div>

                                <div class="col-md-2">
                                    <label>Filter By Colony  </label>
                                    <select name="filter_colony" id="filter_colony" class="form-control">
                                       
                                    </select>
                                </div>

                                <div class="col-md-2">
                                    <label>Filter By Category</label>
                                    <select name="filter_category" class="form-control">
                                        <option value="">All Categories</option>
                                        <?php while ($cat = $categories->fetch_assoc()) { ?>
                                            <option value="<?php echo $cat['bcategory']; ?>"
                                                <?php echo ($filter_category == $cat['bcategory']) ? 'selected' : ''; ?>>
                                                <?php echo $cat['bcategory']; ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>

                                <div class="col-md-2" style="margin-top: 28px;">
                                    <button type="submit" class="btn btn-primary">
                                        Filter
                                    </button>
                                    <button type="submit" name="export" value="csv" class="btn btn-success">
        CSV
    </button>

                                    <a href="addBuilding.php" class="btn btn-light">
                                        Reset
                                    </a>
                                </div>

                            </div>
                        </form>

                        <div class="table-responsive">
                            <table class="table table-striped table-bordered" width="100%">
                                <thead>
                                <tr>
                                    <th>Sr No.</th>
                                    <th>Division</th>
                                    <th>Sub Division</th>
                                    <th>Colony</th>
                                    <th>Building Category</th>
                                    <th>Building No</th>
                                    <th>Login Pin</th>
                                    <th>Update</th>
                                    <th>Delete</th>
                                </tr>
                                </thead>

                                <tbody>
                                <?php
                                $count = 0;

                                if ($buildings && $buildings->num_rows > 0) {
                                    while ($row = $buildings->fetch_assoc()) {
                                        $count++;
                                        ?>
                                        <tr>
                                            <td><?php echo $count; ?></td>
                                            <td><?php echo $row['division_name']; ?></td>
                                            <td><?php echo $row['department_name']; ?></td>
                                            <td><?php echo $row['colony_name']; ?></td>
                                            <td><?php echo $row['bcategory']; ?></td>
                                            <td><?php echo $row['bNo']; ?></td>
                                            <td><?php echo $row['mpin']; ?></td>

                                            <td>
                                                <a href="addBuilding.php?edit=<?php echo $row['bid']; ?>"
                                                   class="btn btn-xs btn-outline-primary">
                                                    Update
                                                </a>
                                            </td>
                                            <td>
                                                <a href="addBuilding.php?delete=<?php echo $row['bid']; ?>"
                                                   onclick="return confirm('Are you sure?');"
                                                   class="btn btn-xs btn-outline-danger">
                                                    Delete
                                                </a>
                                            </td>
                                        </tr>
                                    <?php }
                                } else { ?>
                                    <tr>
                                        <td colspan="9">No Records Found!</td>
                                    </tr>
                                <?php } ?>
                                </tbody>
                            </table>
                        </div>

                    </div>
                </div>

            </div>

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

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

<script>
$(document).ready(function () {

    var editDepartment = "<?php echo $editData['department_id'] ?? ''; ?>";
    var editColony = "<?php echo $editData['colony_id'] ?? ''; ?>";

    var selectedFilterDivision = "<?php echo $filter_division; ?>";
    var selectedFilterDepartment = "<?php echo $filter_department; ?>";
    var selectedFilterColony = "<?php echo $filter_colony; ?>";

    /* Add / Edit Form AJAX */
    function loadDepartments(division_id, selected_department = '') {
        $('#department_id').html('<option value="">Loading...</option>');
        $('#colony_id').html('<option value="">Select Colony</option>');

        $.ajax({
            url: 'getDepartments.php',
            type: 'POST',
            data: {
                division_id: division_id
            },
            success: function (response) {
                $('#department_id').html(response);

                if (selected_department !== '') {
                    $('#department_id').val(selected_department);
                    loadColonies(division_id, selected_department, editColony);
                }
            },
            error: function () {
                $('#department_id').html('<option value="">Department loading error</option>');
            }
        });
    }

    function loadColonies(division_id, department_id, selected_colony = '') {
        $('#colony_id').html('<option value="">Loading...</option>');

        $.ajax({
            url: 'getColonies.php',
            type: 'POST',
            data: {
                division_id: division_id,
                department_id: department_id
            },
            success: function (response) {
                $('#colony_id').html(response);

                if (selected_colony !== '') {
                    $('#colony_id').val(selected_colony);
                }
            },
            error: function () {
                $('#colony_id').html('<option value="">Colony loading error</option>');
            }
        });
    }

    $('#division_id').on('change', function () {
        var division_id = $(this).val();

        if (division_id !== '') {
            loadDepartments(division_id);
        } else {
            $('#department_id').html('<option value="">Select Sub Division</option>');
            $('#colony_id').html('<option value="">Select Colony</option>');
        }
    });

    $('#department_id').on('change', function () {
        var division_id = $('#division_id').val();
        var department_id = $(this).val();

        if (division_id !== '' && department_id !== '') {
            loadColonies(division_id, department_id);
        } else {
            $('#colony_id').html('<option value="">Select Colony</option>');
        }
    });

    var currentDivision = $('#division_id').val();

    if (currentDivision !== '' && editDepartment !== '') {
        loadDepartments(currentDivision, editDepartment);
    }

    /* Filter AJAX */
    function loadFilterDepartments(division_id, selected_department = '') {
        $('#filter_department').html('<option value="">Loading...</option>');
        $('#filter_colony').html('<option value="">All Colonies</option>');

        $.ajax({
            url: 'getDepartments.php',
            type: 'POST',
            data: {
                division_id: division_id
            },
            success: function (response) {
                $('#filter_department').html('<option value="">All Sub Divisions</option>' + response);

                if (selected_department !== '' && selected_department !== '0') {
                    $('#filter_department').val(selected_department);
                    loadFilterColonies(division_id, selected_department, selectedFilterColony);
                }
            },
            error: function () {
                $('#filter_department').html('<option value="">Sub Division loading error</option>');
            }
        });
    }

    function loadFilterColonies(division_id, department_id, selected_colony = '') {
        $('#filter_colony').html('<option value="">Loading...</option>');

        $.ajax({
            url: 'getColonies.php',
            type: 'POST',
            data: {
                division_id: division_id,
                department_id: department_id
            },
            success: function (response) {
                $('#filter_colony').html('<option value="">All Colonies</option>' + response);

                if (selected_colony !== '' && selected_colony !== '0') {
                    $('#filter_colony').val(selected_colony);
                }
            },
            error: function () {
                $('#filter_colony').html('<option value="">Colony loading error</option>');
            }
        });
    }

    $('#filter_division').on('change', function () {
        var division_id = $(this).val();

        if (division_id !== '') {
            loadFilterDepartments(division_id);
        } else {
            $('#filter_department').html('<option value="">All Sub Divisions</option>');
            $('#filter_colony').html('<option value="">All Colonies</option>');
        }
    });

    $('#filter_department').on('change', function () {
        var division_id = $('#filter_division').val();
        var department_id = $(this).val();

        if (division_id !== '' && department_id !== '') {
            loadFilterColonies(division_id, department_id);
        } else {
            $('#filter_colony').html('<option value="">All Colonies</option>');
        }
    });

    if (selectedFilterDivision !== '' && selectedFilterDivision !== '0') {
        loadFilterDepartments(selectedFilterDivision, selectedFilterDepartment);
    }

});
</script>

</body>
</html>
