<?php
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Access Check
if (!has_permission('manage_locations')) {
    echo "<script>alert('Access Denied. Redirecting to Dashboard...'); window.location.href='dashboard.php';</script>";
    exit();
}

// Handle Pickup Station Submission
if (isset($_POST['add_station'])) {
    $station_name = db_prepare($con, $_POST['station_name']);
    $address = db_prepare($con, $_POST['address']);
    $state_id = intval($_POST['state_id']);
    $city_id = intval($_POST['city_id']);
    $contact_no = db_prepare($con, $_POST['contact_no']);

    $query = mysqli_query($con, "INSERT INTO pickup_stations (station_name, address, state_id, city_id, contact_no) VALUES ('$station_name', '$address', '$state_id', '$city_id', '$contact_no')");
    if ($query) {
        log_activity("Added Pickup Hub", "Hub: $station_name, Location: CID $city_id");
        $_SESSION['msg'] = "Pickup station added successfully!";
    } else {
        $_SESSION['errormsg'] = "Something went wrong. Please try again.";
    }
}

// Handle Deletion
if (isset($_GET['del'])) {
    $id = intval($_GET['id']);
    // Fetch name for logging
    $q = mysqli_query($con, "SELECT station_name FROM pickup_stations WHERE id=$id");
    $r = mysqli_fetch_assoc($q);
    $name = $r['station_name'] ?? 'Unknown';

    mysqli_query($con, "DELETE FROM pickup_stations WHERE id = $id");
    log_activity("Deleted Pickup Hub", "Hub: $name, ID: $id");
    $_SESSION['delmsg'] = "Pickup station deleted successfully!";
    header('location: manage-pickup-stations.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Manage Pickup Stations - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"
        crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>
    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-truck-loading me-2"></i> Manage Pickup Stations</h1>
                            <p>Create and manage delivery pickup points</p>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo htmlentities($_SESSION['msg']);
                            unset($_SESSION['msg']); ?>
                        </div>
                    <?php } ?>

                    <?php if (isset($_SESSION['errormsg'])) { ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <?php echo htmlentities($_SESSION['errormsg']);
                            unset($_SESSION['errormsg']); ?>
                        </div>
                    <?php } ?>

                    <?php if (isset($_SESSION['delmsg'])) { ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-trash-alt me-2"></i>
                            <?php echo htmlentities($_SESSION['delmsg']);
                            unset($_SESSION['delmsg']); ?>
                        </div>
                    <?php } ?>

                    <div class="row">
                        <!-- Add New Pickup Station -->
                        <div class="col-lg-12 mb-4">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-primary text-white">
                                    <i class="fas fa-plus-circle me-1"></i> Add New Pickup Station
                                </div>
                                <div class="card-body">
                                    <form method="post">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Station Name</label>
                                                <input type="text" name="station_name" class="form-control" required
                                                    placeholder="e.g., Downtown Pickup Hub">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">State</label>
                                                <select name="state_id" id="state_select" class="form-select" required>
                                                    <option value="">Select State</option>
                                                    <?php
                                                    $s_query = mysqli_query($con, "SELECT * FROM states ORDER BY state_name ASC");
                                                    while ($s_row = mysqli_fetch_array($s_query)) {
                                                        echo "<option value='" . $s_row['id'] . "'>" . htmlentities($s_row['state_name']) . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">City</label>
                                                <select name="city_id" id="city_select" class="form-select" required
                                                    disabled>
                                                    <option value="">Select City</option>
                                                </select>
                                            </div>
                                            <div class="col-md-8 mb-3">
                                                <label class="form-label">Full Address</label>
                                                <input type="text" name="address" class="form-control" required
                                                    placeholder="Street address, landmarks...">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Contact Number (Optional)</label>
                                                <input type="text" name="contact_no" class="form-control"
                                                    placeholder="Hub phone number">
                                            </div>
                                        </div>
                                        <button type="submit" name="add_station" class="btn btn-primary">Save Pickup
                                            Station</button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Pickup Station List -->
                        <div class="col-lg-12">
                            <div class="card shadow-sm border-0">
                                <div class="card-header bg-light">
                                    <i class="fas fa-list me-1"></i> Existing Pickup Stations
                                </div>
                                <div class="card-body">
                                    <table class="table table-hover" id="datatablesSimple">
                                        <thead>
                                            <tr>
                                                <th>Station Name</th>
                                                <th>Location</th>
                                                <th>Address</th>
                                                <th>Contact</th>
                                                <th class="text-end">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $ps_query = mysqli_query($con, "SELECT ps.*, s.state_name, c.city_name 
                                                                           FROM pickup_stations ps 
                                                                           JOIN states s ON ps.state_id = s.id 
                                                                           JOIN cities c ON ps.city_id = c.id 
                                                                           ORDER BY ps.created_at DESC");
                                            while ($ps_row = mysqli_fetch_array($ps_query)) {
                                                ?>
                                                <tr>
                                                    <td><strong>
                                                            <?php echo htmlentities($ps_row['station_name']); ?>
                                                        </strong></td>
                                                    <td>
                                                        <?php echo htmlentities($ps_row['city_name'] . ', ' . $ps_row['state_name']); ?>
                                                    </td>
                                                    <td><small>
                                                            <?php echo htmlentities($ps_row['address']); ?>
                                                        </small></td>
                                                    <td>
                                                        <?php echo htmlentities($ps_row['contact_no'] ?: 'N/A'); ?>
                                                    </td>
                                                    <td class="text-end">
                                                        <a href="manage-pickup-stations.php?id=<?php echo $ps_row['id']; ?>&del=1"
                                                            class="btn btn-sm btn-outline-danger"
                                                            onclick="return confirm('Are you sure you want to delete this pickup station?')">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </td>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script>
        $(document).ready(function () {
            $('#state_select').change(function () {
                var state_id = $(this).val();
                if (state_id) {
                    $('#city_select').prop('disabled', false).html('<option value="">Loading...</option>');
                    $.ajax({
                        url: 'get_locations.php',
                        type: 'POST',
                        data: { state_id: state_id },
                        success: function (html) {
                            $('#city_select').html(html);
                        }
                    });
                } else {
                    $('#city_select').prop('disabled', true).html('<option value="">Select City</option>');
                }
            });
        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest" crossorigin="anonymous"></script>
    <script src="js/datatables-simple-demo.js"></script>
</body>

</html>