<?php
ini_set('display_errors', 0);
error_reporting(0);

session_start();

if(!isset($_SESSION['SESS_MEMBER_ID']) || trim($_SESSION['SESS_MEMBER_ID']) == '') {
    header("location: login.php");
    exit();
}

require_once('dbconnection.php');

$message = "";

// ====================== TOGGLE ACTIVE STATUS ======================
if(isset($_POST['toggle_active']) && isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    $res = mysqli_query($dbcon, "SELECT active FROM tracking WHERE id = $id");
    if($row = mysqli_fetch_assoc($res)) {
        $new_status = $row['active'] == 1 ? 0 : 1;
        mysqli_query($dbcon, "UPDATE tracking SET active = $new_status WHERE id = $id");
        $message = "<span style='color:green'>Record #" . $id . " " . ($new_status ? 'Enabled' : 'Disabled') . " successfully.</span>";
    }
}

// ====================== CREATE NEW TRACKING ======================
if(isset($_POST['submit2'])) {
    $alph = array('A','B','C','E','F','G','H','J','K','M','N','P','Q');
    $numb = array('1','2','3','4','5','6','7','8','9');
   
    $trackingno = $alph[rand(0,12)].$alph[rand(0,12)].$alph[rand(0,12)].$numb[rand(0,8)].$numb[rand(0,8)].$numb[rand(0,8)].$numb[rand(0,8)].$alph[rand(0,12)];

    $consigno    = mysqli_real_escape_string($dbcon, isset($_POST['consigno']) ? $_POST['consigno'] : '');
    $sender      = mysqli_real_escape_string($dbcon, isset($_POST['sender']) ? $_POST['sender'] : '');
    $semail      = mysqli_real_escape_string($dbcon, isset($_POST['semail']) ? $_POST['semail'] : '');
    $remail      = mysqli_real_escape_string($dbcon, isset($_POST['remail']) ? $_POST['remail'] : '');
    $receiver    = mysqli_real_escape_string($dbcon, isset($_POST['receiver']) ? $_POST['receiver'] : '');
    $saddress    = mysqli_real_escape_string($dbcon, isset($_POST['saddress']) ? $_POST['saddress'] : '');
    $address     = mysqli_real_escape_string($dbcon, isset($_POST['address']) ? $_POST['address'] : '');
    $recphone    = mysqli_real_escape_string($dbcon, isset($_POST['recphone']) ? $_POST['recphone'] : '');
    $senderphone = mysqli_real_escape_string($dbcon, isset($_POST['senderphone']) ? $_POST['senderphone'] : '');
    $packagetype = mysqli_real_escape_string($dbcon, isset($_POST['packagetype']) ? $_POST['packagetype'] : '');
    $weight      = mysqli_real_escape_string($dbcon, isset($_POST['weight']) ? $_POST['weight'] : '');
    $cost        = mysqli_real_escape_string($dbcon, isset($_POST['cost']) ? $_POST['cost'] : '');
    $transtype   = mysqli_real_escape_string($dbcon, isset($_POST['transtype']) ? $_POST['transtype'] : '');
    $dispdate    = mysqli_real_escape_string($dbcon, isset($_POST['dispdate']) ? $_POST['dispdate'] : '');
    $pickdate    = mysqli_real_escape_string($dbcon, isset($_POST['pickdate']) ? $_POST['pickdate'] : '');
    $status      = mysqli_real_escape_string($dbcon, isset($_POST['status']) ? $_POST['status'] : 'In Transit');
    $clocation   = mysqli_real_escape_string($dbcon, isset($_POST['clocation']) ? $_POST['clocation'] : 'USA Texas');

    $query = "INSERT INTO tracking 
    (trackingno, consigno, sender, saddress, semail, remail, receiver, recphone, senderphone, address, packagetype, cost, transtype, dispdate, pickdate, status, clocation, weight, active, move, msg)
    VALUES 
    ('$trackingno','$consigno','$sender','$saddress','$semail','$remail','$receiver','$recphone','$senderphone','$address','$packagetype','$cost','$transtype','$dispdate','$pickdate','$status','$clocation','$weight',1,5,'sent')";

    if(mysqli_query($dbcon, $query)) {
        $message = "<span style='color:green'>New Tracking Created Successfully! Tracking No: <strong>$trackingno</strong></span>";
    } else {
        $message = "<span style='color:red'>Error: " . mysqli_error($dbcon) . "</span>";
    }
}

// Bulk Delete
if(isset($_POST['bulk_delete']) && isset($_POST['selected'])) {
    foreach($_POST['selected'] as $id) {
        $id = (int)$id;
        mysqli_query($dbcon, "DELETE FROM tracking WHERE id = $id");
    }
    $message = "<span style='color:green'>Selected records deleted successfully.</span>";
}

// Pagination & Filter
$limit = 7;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$search = isset($_GET['search']) ? mysqli_real_escape_string($dbcon, $_GET['search']) : '';
$status_filter = isset($_GET['status']) ? mysqli_real_escape_string($dbcon, $_GET['status']) : '';

$where = "";
if($search) $where .= " WHERE (trackingno LIKE '%$search%' OR receiver LIKE '%$search%')";
if($status_filter) $where .= ($where ? " AND " : " WHERE ") . "status = '$status_filter'";

$total_query = "SELECT COUNT(*) as total FROM tracking $where";
$total_result = mysqli_query($dbcon, $total_query);
$total_row = mysqli_fetch_assoc($total_result);
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);

$query = "SELECT * FROM tracking $where ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($dbcon, $query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Swift Logistics</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        label { font-weight: bold; display: block; margin: 8px 0 5px; }
        .table-responsive { margin: 15px 0; }
        .btn-toggle { font-size: 0.85rem; padding: 5px 10px; }
    </style>
</head>
<body class="bg-light">

<div class="container py-4">
    <h2 class="mb-4">Track <span class="text-primary">Admin</span></h2>

    <?php if($message != ""): ?>
        <div class="alert alert-info"><?php echo $message; ?></div>
    <?php endif; ?>

    <!-- Filter + Bulk Delete + Table -->
    <form method="POST">
        <button type="submit" name="bulk_delete" class="btn btn-danger mb-3" onclick="return confirm('Delete selected records?')">🗑 Bulk Delete Selected</button>

        <div class="table-responsive">
            <table class="table table-striped table-bordered">
                <thead class="table-dark">
                    <tr>
                        <th><input type="checkbox" onclick="toggleAll(this)"></th>
                        <th>Sno</th>
                        <th>Tracking No</th>
                        <th>Consignment No</th>
                        <th>Sender</th>
                        <th>Receiver</th>
                        <th>Package Type</th>
                        <th>Cost</th>
                        <th>Transit Type</th>
                        <th>Status</th>
                        <th>Location</th>
                        <th>Active</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if(mysqli_num_rows($result) > 0) {
                        $num = $offset + 1;
                        while($row = mysqli_fetch_assoc($result)) {
                            $active_status = $row['active'] == 1 ? '✅ Active' : '❌ Disabled';
                            $toggle_text   = $row['active'] == 1 ? 'Disable' : 'Enable';
                            $toggle_class  = $row['active'] == 1 ? 'btn-danger' : 'btn-success';

                            echo "<tr>";
                            echo '<td><input type="checkbox" name="selected[]" value="'.$row['id'].'"></td>';
                            echo "<td>$num</td>";
                            echo "<td><a href='mf.php?id=".$row['id']."'>".htmlspecialchars($row['trackingno'])."</a></td>";
                            echo "<td>".htmlspecialchars($row['consigno'])."</td>";
                            echo "<td>".htmlspecialchars($row['sender'])."</td>";
                            echo "<td>".htmlspecialchars($row['receiver'])."</td>";
                            echo "<td>".htmlspecialchars($row['packagetype'])."</td>";
                            echo "<td>".htmlspecialchars($row['cost'])."</td>";
                            echo "<td>".htmlspecialchars($row['transtype'])."</td>";
                            echo "<td>".htmlspecialchars($row['status'])."</td>";
                            echo "<td>".htmlspecialchars($row['clocation'])."</td>";
                            echo "<td><strong>$active_status</strong></td>";
                            echo '<td>
                                    <a href="invoice.php?trackingno='.urlencode($row['trackingno']).'" 
                                       class="btn btn-sm btn-primary mb-1">Receipt</a>
                                    
                                    <form method="POST" style="display:inline;" onsubmit="return confirm(\'Toggle this record?\')">
                                        <input type="hidden" name="id" value="'.$row['id'].'">
                                        <button type="submit" name="toggle_active" class="btn btn-sm '.$toggle_class.' btn-toggle">'.$toggle_text.'</button>
                                    </form>
                                  </td>';
                            echo "</tr>";
                            $num++;
                        }
                    } else {
                        echo "<tr><td colspan='13' class='text-center'>No records found.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </form>

    <!-- Pagination -->
    <nav class="mt-4">
        <ul class="pagination justify-content-center">
            <?php if($page > 1): ?>
                <li class="page-item"><a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>">Previous</a></li>
            <?php endif; ?>
            <?php for($i=1; $i<=$total_pages; $i++): ?>
                <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>"><?php echo $i; ?></a>
                </li>
            <?php endfor; ?>
            <?php if($page < $total_pages): ?>
                <li class="page-item"><a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status_filter); ?>">Next</a></li>
            <?php endif; ?>
        </ul>
    </nav>

    <!-- Full Create Form -->
    <div class="card mt-5">
        <div class="card-header bg-primary text-white">
            <h5>Create New Tracking Info</h5>
        </div>
        <div class="card-body">
            <form action="admin.php" method="post" class="row g-3">
                <div class="col-md-6">
                    <label>Consignment No</label>
                    <input type="text" name="consigno" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Sender</label>
                    <input type="text" name="sender" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Sender Email</label>
                    <input type="email" name="semail" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Sender Address</label>
                    <input type="text" name="saddress" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Receiver Email</label>
                    <input type="email" name="remail" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Receiver</label>
                    <input type="text" name="receiver" class="form-control">
                </div>
                <div class="col-12">
                    <label>Receiver Address</label>
                    <textarea name="address" class="form-control" rows="3"></textarea>
                </div>
                <div class="col-md-6">
                    <label>Receiver Phone</label>
                    <input type="text" name="recphone" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Sender Phone</label>
                    <input type="text" name="senderphone" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Package Type</label>
                    <input type="text" name="packagetype" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Weight</label>
                    <input type="text" name="weight" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Total Cost</label>
                    <input type="text" name="cost" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Transit Type</label>
                    <select name="transtype" class="form-select">
                        <option value="AIR FREIGHT">AIR FREIGHT</option>
                        <option value="ROAD TRANSPORT">ROAD TRANSPORT</option>
                        <option value="SEA TRANSPORT">SEA TRANSPORT</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label>Dispatch Date</label>
                    <input type="date" name="dispdate" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Pickup Date</label>
                    <input type="date" name="pickdate" class="form-control">
                </div>
                <div class="col-md-6">
                    <label>Status</label>
                    <input type="text" name="status" class="form-control" value="In Transit">
                </div>
                <div class="col-md-6">
                    <label>Current Location</label>
                    <input type="text" name="clocation" class="form-control" value="USA Texas">
                </div>

                <div class="col-12 mt-4">
                    <button type="submit" name="submit2" class="btn btn-success btn-lg w-100">Create Tracking</button>
                </div>
            </form>
        </div>
    </div>

    <div class="text-center mt-4">
        <form method="POST" action="login.php">
            <button type="submit" name="logoutt" class="btn btn-outline-secondary">Logout</button>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleAll(source) {
    document.querySelectorAll('input[name="selected[]"]').forEach(cb => cb.checked = source.checked);
}
</script>
</body>
</html>