<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
  header("Location: ../auth/login.php");
  exit;
}

$controllers = $pdo->query("SELECT id, username FROM users WHERE role = 'controller' ORDER BY username")->fetchAll();
$sites = $pdo->query("SELECT id, site_name FROM sites ORDER BY site_name")->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['controller_id'], $_POST['site_id'], $_POST['shift_type'])) {
  $controller_id = $_POST['controller_id'];
  $site_id = $_POST['site_id'];
  $shift_type = $_POST['shift_type'];
  $deployment_date = $_POST['deployment_date'] ?? date('Y-m-d');

  $stmt = $pdo->prepare("INSERT INTO controller_deployment (controller_id, site_id, deployment_date, shift_type) VALUES (?, ?, ?, ?)");
  $stmt->execute([$controller_id, $site_id, $deployment_date, $shift_type]);
  $_SESSION['toast'] = "Controller Deployment added successfully!";
  header("Location: controller_deployment.php");
  exit;
}

// Fetch existing deployments
$deployments = $pdo->query("
  SELECT cd.id, u.username AS controller_name, s.site_name, cd.shift_type, cd.deployment_date
  FROM controller_deployment cd
  JOIN users u ON cd.controller_id = u.id
  JOIN sites s ON cd.site_id = s.id
  ORDER BY cd.deployment_date DESC, u.username
")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Controller Deployment | CFS System OS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

   <!-- AdminLTE & Bootstrap -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <style>
    body { font-size: 0.9rem; }
    table#siteTable th, table#siteTable td { font-size: 0.85rem; vertical-align: middle; }
    .form-control { font-size: 0.85rem; padding: 0.3rem 0.5rem; }
    .btn { font-size: 0.8rem; padding: 0.25rem 0.5rem; }
    .modal-title { font-size: 1rem; }
    .modal-body input, .modal-body select { font-size: 0.85rem; }
    .toast-container { position: fixed; bottom: 1rem; right: 1rem; z-index: 9999; }
  </style>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

<?php include '../includes/topbar.php'; ?>
<?php include '../includes/sidebar.php'; ?>

    <div class="content-wrapper">
        <section class="content-header">
            <div class="container-fluid d-flex justify-content-between align-items-center">
            <h4 class="mb-0">Controller Deployment</h4>
            </div>
        </section>
            
        <div class="content">
                <div class="container-fluid">
                    <form method="POST" class="row g-3 mb-4">
                        <div class="col-md-3">
                        <label>Controller:</label>
                        <select name="controller_id" class="form-select" required>
                            <option value="">Select Controller</option>
                            <?php foreach ($controllers as $controller): ?>
                            <option value="<?= $controller['id'] ?>"><?= htmlspecialchars($controller['username']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        </div>
                        <div class="col-md-3">
                        <label>Site:</label>
                        <select name="site_id" class="form-select" required>
                            <option value="">Select Site</option>
                            <?php foreach ($sites as $site): ?>
                            <option value="<?= $site['id'] ?>"><?= htmlspecialchars($site['site_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        </div>
                        <div class="col-md-3">
                        <label>Shift Type:</label>
                        <select name="shift_type" class="form-select" required>
                            <option value="">Select Shift</option>
                            <option value="Day">Day</option>
                            <option value="Night">Night</option>
                            <option value="Rest">Rest</option>
                        </select>
                        </div>
                        <div class="col-md-3">
                        <label>Date:</label>
                        <input type="date" name="deployment_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                        </div>
                        <div class="col-12">
                        <button type="submit" class="btn btn-primary">Assign Deployment</button>
                        </div>
                    </form>

                    <h4>Deployment Records</h4>
                    <table id="deploymentTable" class="table table-bordered table-striped">
                        <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>Controller</th>
                            <th>Site</th>
                            <th>Shift</th>
                            <th>Date</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($deployments as $i => $row): ?>
                            <tr>
                            <td><?= $i + 1 ?></td>
                            <td><?= htmlspecialchars($row['controller_name']) ?></td>
                            <td><?= htmlspecialchars($row['site_name']) ?></td>
                            <td><?= htmlspecialchars($row['shift_type']) ?></td>
                            <td><?= htmlspecialchars($row['deployment_date']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>

                    <!-- Toast Container -->
                    <div class="toast-container">
                        <?php if (isset($_SESSION['toast'])): ?>
                        <div class="toast align-items-center text-bg-success border-0 show" role="alert" aria-live="assertive" aria-atomic="true">
                            <div class="d-flex">
                            <div class="toast-body">
                                <?= htmlspecialchars($_SESSION['toast']) ?>
                            </div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                            </div>
                        </div>
                        <?php unset($_SESSION['toast']); ?>
                        <?php endif; ?>
                    </div>
                </div>
        </div>
    </div>
</div>

  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>

  <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    $('#deploymentTable').DataTable({ pageLength: 10 });

    const toastElList = [].slice.call(document.querySelectorAll('.toast'));
    toastElList.map(toastEl => new bootstrap.Toast(toastEl, { delay: 3000 }).show());
  </script>
</body>
</html>
