<?php
include("db/cn.php");
include("common/tx.php");

// ---------- IMPORTANT: Start session ----------
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ---------- Secure database connection assignment ----------
// 'cn.php' usually defines $con, $connection or $conn.
// We try to find whichever variable actually holds the mysqli object.
if (isset($conn) && $conn instanceof mysqli) {
    $db = $conn;               // already set
} elseif (isset($connection) && $connection instanceof mysqli) {
    $db = $connection;
} elseif (isset($con) && $con instanceof mysqli) {
    $db = $con;
} else {
    die("Database connection not found. Check db/cn.php");
}
// Now use $db consistently in all queries
$conn = $db;   // alias to keep rest of code unchanged

// ---------- Get session data ----------
if (
    isset($_SESSION['user_name']) &&
    isset($_SESSION['user_role']) &&
    isset($_SESSION['outlet_name']) &&
    isset($_SESSION['outlet_address'])
) {
    $userName        = $_SESSION['user_name'];
    $userRole        = $_SESSION['user_role'];
    $outlet_address  = $_SESSION['outlet_address'];
    $outlet_name     = $_SESSION['outlet_name'];
} else {
    // Optional: handle missing session gracefully
    $userName = $userRole = $outlet_address = $outlet_name = '';
}

// ---------- Handle Insert ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_transport'])) {
    $city      = trim($_POST['city'] ?? '');
    $transport = trim($_POST['transport'] ?? '');
    $date_time = date('Y-m-d');
    $user_name = $userName;

    if ($city !== '' && $transport !== '') {
        $stmt = $conn->prepare("INSERT INTO loc_trans (city, transport, date_time, user_name) VALUES (?, ?, ?, ?)");
        if ($stmt) {
            $stmt->bind_param("ssss", $city, $transport, $date_time, $user_name);
            if ($stmt->execute()) {
                $msg = "<div class='alert alert-success'>Record added successfully.</div>";
            } else {
                $msg = "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
            }
            $stmt->close();
        } else {
            $msg = "<div class='alert alert-danger'>Prepare failed: " . $conn->error . "</div>";
        }
    } else {
        $msg = "<div class='alert alert-warning'>Please fill all fields.</div>";
    }
}

// ---------- Handle Delete ----------
if (isset($_GET['delete_id'])) {
    $delete_id = (int) $_GET['delete_id'];
    $stmt = $conn->prepare("DELETE FROM loc_trans WHERE id = ?");
    if ($stmt) {
        $stmt->bind_param("i", $delete_id);
        if ($stmt->execute()) {
            $msg = "<div class='alert alert-success'>Record deleted successfully.</div>";
        } else {
            $msg = "<div class='alert alert-danger'>Error deleting record: " . $stmt->error . "</div>";
        }
        $stmt->close();
    } else {
        $msg = "<div class='alert alert-danger'>Prepare failed: " . $conn->error . "</div>";
    }
}

// ---------- Fetch all records ----------
$result = $conn->query("SELECT * FROM loc_trans ORDER BY id DESC");
?>
<!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><?php echo $tx; ?></title>

    <!-- Custom fonts -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom styles -->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        body {
            font-family: 'Quicksand', sans-serif;
            font-weight:700;
        }
        .bg-gradient-primary {
            background: #0A4657;
            color: #fff;
        }
        .btn-primary {
            background: #0A4657;
            color: #fff;
            border: 1px solid #0A4657;
        }
        .btn-primary:hover {
            background: #fff;
            border: 1px solid #0A4657;
            color: #0A4657;
        }
        .chart-container {
            position: relative;
            background: rgba(255,255,255,0.9);
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
        }
        canvas {
            max-width: 100%;
            height: auto;
        }
        .fa-download:hover {
            color: #953E39;
        }
        td {
            font-weight: 700;
            color:#000;
        }
        input, .form-control{
            color:#000;
            font-weight:700;
        }
        .btn{
            font-weight:700;
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include("common/sd.php"); ?>

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <!-- Topbar -->
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <?php include('common/log.php'); ?>
                </nav>

                <!-- Main content area -->
                <div class="container-fluid">
                    <?php if (!empty($msg)) echo $msg; ?>

                    <div class="row">
                        <!-- Form column (col-sm-4) -->
                        <div class="col-sm-4">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3 bg-gradient-primary">
                                    <h6 class="m-0 font-weight-bold text-white">Add Transport Record</h6>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="" class="font-weight-bold" style="color:#000;">
                                        <div class="form-group">
                                            <label for="city">City</label>
                                            <input type="text" class="form-control" id="city" name="city" placeholder="Enter city" required>
                                        </div>
                                        <div class="form-group">
                                            <label for="transport">Transport</label>
                                            <input type="text" class="form-control" id="transport" name="transport" placeholder="Enter transport details" required>
                                        </div>
                                        <button type="submit" name="add_transport" class="btn btn-primary btn-block">
                                            <i class="fas fa-plus-circle"></i> Add Record
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Table column (col-sm-8) -->
                        <div class="col-sm-8">
                            <div class="card shadow mb-4">
                                <div class="card-header py-3 bg-gradient-primary">
                                    <h6 class="m-0 font-weight-bold text-white">Transport Records</h6>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                                            <thead class="thead-light" style="color:#000;">
                                                <tr>
                                                    <th style="color:#000;">ID</th>
                                                    <th style="color:#000;">City</th>
                                                    <th style="color:#000;">Transport</th>
                                                    <th style="color:#000;">Date</th>
                                                    <th style="color:#000;">User</th>
                                                    <th style="color:#000;">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while ($row = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo $row['id']; ?></td>
                                                            <td><?php echo htmlspecialchars($row['city']); ?></td>
                                                            <td><?php echo htmlspecialchars($row['transport']); ?></td>
                                                            <td><?php echo $row['date_time']; ?></td>
                                                            <td><?php echo htmlspecialchars($row['user_name']); ?></td>
                                                            <td>
                                                                <a href="?delete_id=<?php echo $row['id']; ?>" 
                                                                   class="btn btn-danger btn-sm"
                                                                   onclick="return confirm('Are you sure you want to delete this record?');">
                                                                    <i class="fas fa-trash-alt"></i> Delete
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center">No records found.</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div><!-- /.row -->
                </div><!-- /.container-fluid -->
            </div><!-- /#content -->

            <!-- Footer -->
            <?php include("common/main_ft.php"); ?>
        </div><!-- /#content-wrapper -->
    </div><!-- /#wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>