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

// Enable error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log');

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 State Submission
if (isset($_POST['add_state'])) {
    $state_name = db_prepare($con, $_POST['state_name']);
    $query = mysqli_query($con, "INSERT INTO states (state_name) VALUES ('$state_name')");
    if ($query) {
        log_activity("Added State", "State Name: $state_name");
        $_SESSION['msg'] = "State added successfully!";
    } else {
        $_SESSION['errormsg'] = "Something went wrong. Please try again.";
    }
}

// Handle City Submission
if (isset($_POST['add_city'])) {
    $state_id = intval($_POST['state_id']);
    $city_name = db_prepare($con, $_POST['city_name']);
    $query = mysqli_query($con, "INSERT INTO cities (state_id, city_name) VALUES ('$state_id', '$city_name')");
    if ($query) {
        log_activity("Added City", "City Name: $city_name (State ID: $state_id)");
        $_SESSION['msg'] = "City added successfully!";
    } else {
        $_SESSION['errormsg'] = "Something went wrong. Please try again.";
    }
}

// Handle Deletions
if (isset($_GET['del_state'])) {
    $id = intval($_GET['id']);
    // Fetch name for logging before delete
    $q = mysqli_query($con, "SELECT state_name FROM states WHERE id=$id");
    $r = mysqli_fetch_assoc($q);
    $name = $r['state_name'] ?? 'Unknown';

    mysqli_query($con, "DELETE FROM states WHERE id = $id");
    log_activity("Deleted State", "State: $name, ID: $id");
    $_SESSION['delmsg'] = "State and its cities deleted successfully!";
    header('location: manage-locations.php');
    exit();
}

if (isset($_GET['del_city'])) {
    $id = intval($_GET['id']);
    // Fetch name for logging
    $q = mysqli_query($con, "SELECT city_name FROM cities WHERE id=$id");
    $r = mysqli_fetch_assoc($q);
    $name = $r['city_name'] ?? 'Unknown';

    mysqli_query($con, "DELETE FROM cities WHERE id = $id");
    log_activity("Deleted City", "City: $name, ID: $id");
    $_SESSION['delmsg'] = "City deleted successfully!";
    header('location: manage-locations.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 Locations - 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>
</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-map-marker-alt me-2"></i> Manage Locations</h1>
                            <p>Manage States and Cities for shipping addresses</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">
                        <!-- Manage States -->
                        <div class="col-lg-5 mb-4">
                            <div class="card mb-4 shadow-sm border-0">
                                <div class="card-header bg-primary text-white">
                                    <i class="fas fa-map me-1"></i> Add New State
                                </div>
                                <div class="card-body">
                                    <form method="post">
                                        <div class="mb-3">
                                            <label class="form-label">State Name</label>
                                            <input type="text" name="state_name" class="form-control" required
                                                placeholder="Enter state name">
                                        </div>
                                        <button type="submit" name="add_state" class="btn btn-primary btn-sm">Add
                                            State</button>
                                    </form>
                                </div>
                            </div>

                            <div class="card shadow-sm border-0">
                                <div class="card-header">
                                    <i class="fas fa-list me-1"></i> Existing States
                                </div>
                                <div class="card-body p-0">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>State Name</th>
                                                <th class="text-end">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $s_query = mysqli_query($con, "SELECT * FROM states ORDER BY state_name ASC");
                                            $cnt = 1;
                                            while ($s_row = mysqli_fetch_array($s_query)) {
                                                ?>
                                                <tr>
                                                    <td><?php echo $cnt; ?></td>
                                                    <td><?php echo htmlentities($s_row['state_name']); ?></td>
                                                    <td class="text-end">
                                                        <a href="manage-locations.php?id=<?php echo $s_row['id']; ?>&del_state=1"
                                                            class="btn btn-sm btn-outline-danger"
                                                            onclick="return confirm('Deleting this state will also delete all cities under it. Are you sure?')">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php $cnt++;
                                            } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- Manage Cities -->
                        <div class="col-lg-7">
                            <div class="card mb-4 shadow-sm border-0">
                                <div class="card-header bg-success text-white">
                                    <i class="fas fa-city me-1"></i> Add New City
                                </div>
                                <div class="card-body">
                                    <form method="post">
                                        <div class="row">
                                            <div class="col-md-5 mb-3">
                                                <label class="form-label">Select State</label>
                                                <select name="state_id" 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-5 mb-3">
                                                <label class="form-label">City Name</label>
                                                <input type="text" name="city_name" class="form-control" required
                                                    placeholder="Enter city name">
                                            </div>
                                            <div class="col-md-2 mb-3">
                                                <label class="form-label d-none d-md-block">&nbsp;</label>
                                                <button type="submit" name="add_city"
                                                    class="btn btn-success btn-sm w-100">Add</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <div class="card shadow-sm border-0">
                                <div class="card-header">
                                    <i class="fas fa-list me-1"></i> Existing Cities
                                </div>
                                <div class="card-body">
                                    <table class="table table-hover" id="datatablesSimple">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>State</th>
                                                <th>City Name</th>
                                                <th class="text-end">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $c_query = mysqli_query($con, "SELECT cities.*, states.state_name FROM cities JOIN states ON cities.state_id = states.id ORDER BY states.state_name ASC, cities.city_name ASC");
                                            $cnt = 1;
                                            while ($c_row = mysqli_fetch_array($c_query)) {
                                                ?>
                                                <tr>
                                                    <td><?php echo $cnt; ?></td>
                                                    <td><span
                                                            class="badge bg-secondary"><?php echo htmlentities($c_row['state_name']); ?></span>
                                                    </td>
                                                    <td><?php echo htmlentities($c_row['city_name']); ?></td>
                                                    <td class="text-end">
                                                        <a href="manage-locations.php?id=<?php echo $c_row['id']; ?>&del_city=1"
                                                            class="btn btn-sm btn-outline-danger"
                                                            onclick="return confirm('Are you sure you want to delete this city?')">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php $cnt++;
                                            } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        crossorigin="anonymous"></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>