<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/project_menu.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$pdo = crm_pdo();
$page_title = 'Dispatch';

$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);

if ($projectId <= 0) {
    $role = gp_user_role($pdo);

    if (gp_is_full_project_access_role($role)) {
        $rows = $pdo->query("SELECT p.id, p.code, p.title, c.name AS customer_name FROM projects p LEFT JOIN customers c ON c.id = p.customer_id ORDER BY p.id DESC")->fetchAll();
    } elseif (gp_is_secretary_like_role($role)) {
        $stmt = $pdo->prepare("
            SELECT p.id, p.code, p.title, c.name AS customer_name
            FROM project_edit_permissions pep
            JOIN projects p ON p.id = pep.project_id
            LEFT JOIN customers c ON c.id = p.customer_id
            WHERE pep.user_id = :uid AND pep.can_edit = 1
            ORDER BY p.id DESC
        ");
        $stmt->execute([':uid' => (int)($_SESSION['user_id'] ?? 0)]);
        $rows = $stmt->fetchAll();
    } else {
        $rows = [];
    }

    include __DIR__ . '/../includes/header.php';
    ?>
    <div class="page-header">
      <div class="page-header-title">
        <h1>Dispatch</h1>
        <span>Select a project first</span>
      </div>
    </div>

    <div class="card">
      <?php if (!$rows): ?>
        <p class="small">No accessible projects found.</p>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table">
            <thead><tr><th>Code</th><th>Title</th><th>Customer</th><th></th></tr></thead>
            <tbody>
              <?php foreach ($rows as $r): ?>
                <tr>
                  <td><?php echo h($r['code']); ?></td>
                  <td><?php echo h($r['title']); ?></td>
                  <td><?php echo h($r['customer_name']); ?></td>
                  <td><a class="btn btn-sm btn-outline-light" href="/public/projects/dispatch.php?project_id=<?php echo (int)$r['id']; ?>">Open dispatch</a></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
    <?php
    include __DIR__ . '/../includes/footer.php';
    exit;
}

gp_require_project_edit($pdo, $projectId);

$stmt = $pdo->prepare("SELECT p.*, c.name AS customer_name FROM projects p LEFT JOIN customers c ON c.id = p.customer_id WHERE p.id = :id LIMIT 1");
$stmt->execute([':id' => $projectId]);
$project = $stmt->fetch();
if (!$project) die('Project not found.');

$employees = $pdo->query("SELECT id, full_name FROM employees WHERE active = 1 ORDER BY full_name ASC")->fetchAll();
$partners = $pdo->query("SELECT id, company_name FROM external_partners WHERE active = 1 ORDER BY company_name ASC")->fetchAll();

$errors = [];
$ok = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string)($_POST['action'] ?? 'assign'));

    if ($action === 'delete') {
        $rowId = (int)($_POST['row_id'] ?? 0);
        if ($rowId > 0) {
            $stmt = $pdo->prepare("DELETE FROM project_assignments WHERE id = :id AND project_id = :pid");
            $stmt->execute([':id' => $rowId, ':pid' => $projectId]);
            $ok = 'Assignment deleted.';
        }
    } else {
        $type = trim((string)($_POST['type'] ?? 'employee'));
        $employeeId = (int)($_POST['employee_id'] ?? 0);
        $partnerId = (int)($_POST['partner_id'] ?? 0);
        $date = trim((string)($_POST['date'] ?? ''));
        $time = trim((string)($_POST['time'] ?? ''));
        $role = trim((string)($_POST['role'] ?? ''));
        $notes = trim((string)($_POST['notes'] ?? ''));

        if (!in_array($type, ['employee', 'partner'], true)) $errors[] = 'Invalid assignment type.';
        if ($type === 'employee' && $employeeId <= 0) $errors[] = 'Choose an employee.';
        if ($type === 'partner' && $partnerId <= 0) $errors[] = 'Choose a partner.';
        if ($date === '') $errors[] = 'Assigned date is required.';

        if (!$errors) {
            $stmt = $pdo->prepare("INSERT INTO project_assignments (project_id, assignment_type, employee_id, external_partner_id, assigned_date, assigned_time, role_label, notes, status) VALUES (:project_id, :type, :employee_id, :partner_id, :assigned_date, :assigned_time, :role_label, :notes, 'assigned')");
            $stmt->execute([
                ':project_id' => $projectId,
                ':type' => $type,
                ':employee_id' => $type === 'employee' ? $employeeId : null,
                ':partner_id' => $type === 'partner' ? $partnerId : null,
                ':assigned_date' => $date,
                ':assigned_time' => $time !== '' ? $time : null,
                ':role_label' => $role !== '' ? $role : null,
                ':notes' => $notes !== '' ? $notes : null,
            ]);
            $ok = 'Assignment created.';
        }
    }
}

$stmt = $pdo->prepare("SELECT pa.*, e.full_name, ep.company_name FROM project_assignments pa LEFT JOIN employees e ON e.id = pa.employee_id LEFT JOIN external_partners ep ON ep.id = pa.external_partner_id WHERE pa.project_id = :pid ORDER BY pa.assigned_date DESC, pa.assigned_time DESC, pa.id DESC");
$stmt->execute([':pid' => $projectId]);
$rows = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Dispatch</h1>
    <span><?php echo h(($project['code'] ?? '') . ' · ' . ($project['title'] ?? '') . ' · ' . ($project['customer_name'] ?? '')); ?></span>
  </div>
  <div class="page-header-actions">
    <a class="btn btn-secondary btn-sm" href="/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">Back to project</a>
  </div>
</div>

<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-danger" style="background:rgba(22,163,74,.15);color:#166534;border-color:rgba(22,163,74,.25)"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>
    <form method="post">
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Type</label><select name="type"><option value="employee">Employee</option><option value="partner">Partner</option></select></div>
        <div class="form-group"><label>Employee</label><select name="employee_id"><option value="0">Select employee</option><?php foreach ($employees as $e): ?><option value="<?php echo (int)$e['id']; ?>"><?php echo h($e['full_name']); ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label>Partner</label><select name="partner_id"><option value="0">Select partner</option><?php foreach ($partners as $p): ?><option value="<?php echo (int)$p['id']; ?>"><?php echo h($p['company_name']); ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label>Date</label><input type="date" name="date" value="<?php echo date('Y-m-d'); ?>"></div>
        <div class="form-group"><label>Time</label><input type="time" name="time"></div>
        <div class="form-group"><label>Role / task</label><input type="text" name="role"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Notes</label><textarea name="notes"></textarea></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Assign</button></div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Assignments</h1><span>Project dispatch list</span></div>
    <?php if (!$rows): ?>
      <p class="small">No assignments yet.</p>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Type</th><th>Name</th><th>Date</th><th>Time</th><th>Role</th><th>Status</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <tr>
                <td><?php echo h($r['assignment_type']); ?></td>
                <td><?php echo h($r['assignment_type'] === 'employee' ? ($r['full_name'] ?? '') : ($r['company_name'] ?? '')); ?></td>
                <td><?php echo h($r['assigned_date']); ?></td>
                <td><?php echo h($r['assigned_time']); ?></td>
                <td><?php echo h($r['role_label']); ?></td>
                <td><?php echo h($r['status']); ?></td>
                <td>
                  <form method="post" onsubmit="return confirm('Delete assignment?')">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
                    <input type="hidden" name="row_id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn btn-sm btn-outline-light" type="submit">Delete</button>
                  </form>
                </td>
              </tr>
              <tr><td colspan="7" class="small"><?php echo h($r['notes'] ?? ''); ?></td></tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
