<?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' => gp_current_user_id()]);
        $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="/gopools/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') {
    gp_require_csrf();
    $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 {
        $assignee = trim((string)($_POST['assignee'] ?? ''));
        $type = '';
        $employeeId = 0;
        $partnerId = 0;
        
        if (strpos($assignee, 'employee_') === 0) {
            $type = 'employee';
            $employeeId = (int)substr($assignee, 9);
        } elseif (strpos($assignee, 'partner_') === 0) {
            $type = 'partner';
            $partnerId = (int)substr($assignee, 8);
        }
        $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[] = 'Please select an assignee.';
        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';
?>
<?php gp_render_project_menu($pdo, $projectId); ?>

<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="/gopools/public/projects/edit.php?id=<?php echo (int)$projectId; ?>">? ??s? st? ????</a>
  </div>
</div>

<?php
// ── Duration suggestions panel ────────────────────────────────────────────────
// Handle accept/reject
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $suggAction = trim((string)($_POST['sugg_action'] ?? ''));
    $suggId = (int)($_POST['sugg_id'] ?? 0);
    if ($suggId > 0 && in_array($suggAction, ['accept','reject'], true)) {
        gp_require_csrf();
        $newStatus = $suggAction === 'accept' ? 'accepted' : 'rejected';
        $reviewerId = (int)(auth_user()['id'] ?? 0);
        $pdo->prepare("UPDATE project_duration_suggestions SET status=?, reviewed_by=?, reviewed_at=NOW() WHERE id=? AND project_id=?")
            ->execute([$newStatus, $reviewerId, $suggId, $projectId]);

        // If accepted → update project dates
        if ($suggAction === 'accept') {
            $sg = $pdo->prepare("SELECT * FROM project_duration_suggestions WHERE id=?");
            $sg->execute([$suggId]);
            $sugRow = $sg->fetch();
            if ($sugRow) {
                $sets = [];
                $params = [];
                if (!empty($sugRow['proposed_start_date'])) { $sets[] = 'start_date=?';       $params[] = $sugRow['proposed_start_date']; }
                if (!empty($sugRow['proposed_end_date']))   { $sets[] = 'end_date_planned=?'; $params[] = $sugRow['proposed_end_date']; }
                if ($sets) {
                    $params[] = $projectId;
                    $pdo->prepare("UPDATE projects SET " . implode(', ', $sets) . " WHERE id=?")->execute($params);
                }
            }
            $ok = 'Suggestion accepted and project dates updated.';
        } else {
            $ok = 'Suggestion rejected.';
        }
    }
}

$suggestions = $pdo->prepare("
    SELECT ds.*, u.username,
           CASE ds.suggested_by_type
               WHEN 'employee' THEN e.full_name
               WHEN 'partner'  THEN ep.company_name
               ELSE u.username
           END AS person_name
    FROM project_duration_suggestions ds
    JOIN users u ON u.id = ds.suggested_by_user_id
    LEFT JOIN employees e ON e.id = (SELECT employee_id FROM users WHERE id=ds.suggested_by_user_id LIMIT 1)
    LEFT JOIN external_partners ep ON ep.id = (SELECT external_partner_id FROM users WHERE id=ds.suggested_by_user_id LIMIT 1)
    WHERE ds.project_id = ?
    ORDER BY ds.created_at DESC
    LIMIT 20
");
$suggestions->execute([$projectId]);
$suggRows = $suggestions->fetchAll();
$pendingCount = count(array_filter($suggRows, fn($s) => $s['status'] === 'pending'));

// ── Missing Parts requests ──────────────────────────────────────────────────
$mps = $pdo->prepare("
    SELECT mp.*, u.username,
           CASE mp.requested_by_type
               WHEN 'employee' THEN e.full_name
               WHEN 'partner'  THEN ep.company_name
               ELSE u.username
           END AS person_name
    FROM project_missing_parts mp
    JOIN users u ON u.id = mp.requested_by_user_id
    LEFT JOIN employees e ON e.id = (SELECT employee_id FROM users WHERE id=mp.requested_by_user_id LIMIT 1)
    LEFT JOIN external_partners ep ON ep.id = (SELECT external_partner_id FROM users WHERE id=mp.requested_by_user_id LIMIT 1)
    WHERE mp.project_id = ?
    ORDER BY mp.created_at DESC
");
$mps->execute([$projectId]);
$missingPartsRows = $mps->fetchAll();
$pendingPartsCount = count(array_filter($missingPartsRows, fn($s) => $s['status'] === 'pending'));
?>

<?php if ($suggRows): ?>
<div class="card" style="margin-bottom:1.5rem">
  <div class="page-header-title" style="margin-bottom:1rem">
    <h1 style="font-size:1.05rem">⏱ Duration Suggestions</h1>
    <span><?php echo count($suggRows); ?> total
      <?php if ($pendingCount > 0): ?>
        · <strong style="color:#f59e0b"><?php echo $pendingCount; ?> pending</strong>
      <?php endif; ?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>From</th>
          <th>Type</th>
          <th>Proposed Start</th>
          <th>Proposed End</th>
          <th>Days</th>
          <th>Notes</th>
          <th>Status</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($suggRows as $sg): ?>
        <tr>
          <td><strong><?php echo h($sg['person_name'] ?: $sg['username']); ?></strong></td>
          <td><span style="font-size:.72rem;font-weight:600;text-transform:uppercase;color:var(--gp-muted)"><?php echo h($sg['suggested_by_type']); ?></span></td>
          <td><?php echo $sg['proposed_start_date'] ? date('d/m/Y', strtotime($sg['proposed_start_date'])) : '—'; ?></td>
          <td><?php echo $sg['proposed_end_date']   ? date('d/m/Y', strtotime($sg['proposed_end_date']))   : '—'; ?></td>
          <td><?php echo $sg['proposed_days'] ? (int)$sg['proposed_days'] . 'd' : '—'; ?></td>
          <td style="max-width:200px;font-size:.82rem;color:var(--gp-muted)"><?php echo h($sg['notes'] ?? ''); ?></td>
          <td>
            <?php if ($sg['status'] === 'pending'): ?>
              <span style="background:#f59e0b;color:#fff;border-radius:999px;padding:2px 8px;font-size:.68rem;font-weight:700">PENDING</span>
            <?php elseif ($sg['status'] === 'accepted'): ?>
              <span style="background:#16a34a;color:#fff;border-radius:999px;padding:2px 8px;font-size:.68rem;font-weight:700">ACCEPTED</span>
            <?php else: ?>
              <span style="background:#dc2626;color:#fff;border-radius:999px;padding:2px 8px;font-size:.68rem;font-weight:700">REJECTED</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($sg['status'] === 'pending'): ?>
              <form method="post" style="display:flex;gap:.25rem">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="sugg_id" value="<?php echo (int)$sg['id']; ?>">
                <button name="sugg_action" value="accept" class="btn btn-sm btn-outline-light" title="Accept & update project dates"
                        onclick="return confirm('Accept this suggestion and update project dates?')">✅ Accept</button>
                <button name="sugg_action" value="reject" class="btn btn-sm btn-outline-light" title="Reject">✖ Reject</button>
              </form>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<?php if ($missingPartsRows): ?>
<div class="card" style="margin-bottom:1.5rem">
  <div class="page-header-title" style="margin-bottom:1rem">
    <h1 style="font-size:1.05rem">📦 Missing Parts Requests</h1>
    <span><?php echo count($missingPartsRows); ?> total
      <?php if ($pendingPartsCount > 0): ?>
        · <strong style="color:#f59e0b"><?php echo $pendingPartsCount; ?> pending fulfillment</strong>
      <?php endif; ?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table">
      <thead>
        <tr>
          <th>From</th>
          <th>Type</th>
          <th>Part Description</th>
          <th>Status</th>
          <th>Tracking / Courier Info</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($missingPartsRows as $mp): ?>
        <tr>
          <td><strong><?php echo h($mp['person_name'] ?: $mp['username']); ?></strong><br><span style="font-size:.65rem;color:var(--gp-muted);"><?php echo date('d/m/y H:i', strtotime($mp['created_at'])); ?></span></td>
          <td><span style="font-size:.72rem;font-weight:600;text-transform:uppercase;color:var(--gp-muted)"><?php echo h($mp['requested_by_type']); ?></span></td>
          <td style="max-width:250px;white-space:pre-wrap;font-size:.85rem;font-weight:500;">
            <?php echo h($mp['part_description']); ?>
            <?php if (!empty($mp['photo_filename'])): ?>
              <div style="margin-top:.5rem;">
                <a href="/gopools/public/uploads/missing_parts/<?php echo h($mp['photo_filename']); ?>" target="_blank">
                  <img src="/gopools/public/uploads/missing_parts/<?php echo h($mp['photo_filename']); ?>" style="max-height:60px;border-radius:4px;border:1px solid var(--gp-border);">
                </a>
              </div>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($mp['status'] === 'pending'): ?>
              <span style="background:#f59e0b;color:#fff;border-radius:999px;padding:2px 8px;font-size:.68rem;font-weight:700">PENDING</span>
            <?php else: ?>
              <span style="background:#16a34a;color:#fff;border-radius:999px;padding:2px 8px;font-size:.68rem;font-weight:700">SENT</span>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($mp['status'] === 'pending'): ?>
              <form class="fulfill-missing-part" style="display:flex;gap:.5rem;align-items:center;">
                <input type="hidden" name="request_id" value="<?php echo (int)$mp['id']; ?>">
                <input type="text" name="tracking_number" class="form-control" style="max-width:200px;font-size:.8rem;padding:.25rem .5rem" placeholder="Tracking #" required>
                <button type="submit" class="btn btn-sm btn-primary">Mark as Sent</button>
                <div class="feedback" style="display:none;font-size:.7rem;margin-left:.25rem;"></div>
              </form>
            <?php else: ?>
              <span style="font-weight:600;color:var(--gp-text);"><?php echo h($mp['tracking_number']); ?></span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function(){
  document.querySelectorAll('.fulfill-missing-part').forEach(function(f){
    f.addEventListener('submit', function(e){
      e.preventDefault();
      var btn = f.querySelector('button');
      var fb = f.querySelector('.feedback');
      var data = new FormData(f);
      data.append('csrf_token', window.csrfToken || '<?php echo csrf_token(); ?>');
      btn.disabled = true; btn.textContent = 'Saving...';
      fetch('/gopools/public/api/fulfill_missing_part.php', { method:'POST', body:data })
      .then(r => r.json()).then(function(res){
          if(res.ok){
              fb.style.display = 'block'; fb.textContent = '✅';
              setTimeout(() => { window.location.reload(); }, 600);
          } else {
              fb.style.display = 'block'; fb.textContent = '❌ ' + (res.error || 'Failed');
              btn.disabled = false; btn.textContent = 'Mark as Sent';
          }
      }).catch(function(){
          fb.style.display = 'block'; fb.textContent = '❌ Network error';
          btn.disabled = false; btn.textContent = 'Mark as Sent';
      });
    });
  });
});
</script>

<div class="grid-2">
  <div class="card">
    <?php if ($ok): ?><div class="alert-success"><?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">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group">
          <label>Assign to</label>
          <select name="assignee">
            <option value="">Select person...</option>
            <optgroup label="Employees">
              <?php foreach ($employees as $e): ?><option value="employee_<?php echo (int)$e['id']; ?>"><?php echo h($e['full_name']); ?></option><?php endforeach; ?>
            </optgroup>
            <optgroup label="Partners">
              <?php foreach ($partners as $p): ?><option value="partner_<?php echo (int)$p['id']; ?>"><?php echo h($p['company_name']); ?></option><?php endforeach; ?>
            </optgroup>
          </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(gp_date((string)$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?')">
      <?php echo csrf_field(); ?>
                    <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'] ?? ''); ?>
                  <?php if (!empty($r['offer_filename'])): ?>
                    <div style="margin-top:4px;">
                      <strong>📄 Προσφορά:</strong> <a href="/gopools/public/uploads/project_offers/<?php echo h($r['offer_filename']); ?>" target="_blank" style="color:var(--gp-primary);font-weight:600;">Download Offer Document</a>
                    </div>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

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