<?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';
require_once __DIR__ . '/../../app/lib/mailer.php';
auth_require_login();
$pdo = crm_pdo();
$_lang = gp_lang($pdo);
$page_title = 'Assign & Send';

$projectId = (int)($_GET['project_id'] ?? $_POST['project_id'] ?? 0);
if ($projectId <= 0) die('Missing project_id.');
gp_require_project_edit($pdo, $projectId);

$stmt = $pdo->prepare("SELECT p.*, c.name AS customer_name, c.contact_person, c.phone AS customer_phone, c.email AS customer_email 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, email FROM employees WHERE active = 1 ORDER BY full_name ASC")->fetchAll();
$partners = $pdo->query("SELECT id, company_name, email FROM external_partners WHERE active = 1 ORDER BY company_name ASC")->fetchAll();

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

// ── HANDLE ASSIGNMENT (from dispatch.php) ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_action'])) {
    gp_require_csrf();
    $action = trim((string)($_POST['assign_action'] ?? ''));
    if ($action === 'delete') {
        $rowId = (int)($_POST['row_id'] ?? 0);
        $stmt = $pdo->prepare("DELETE FROM project_assignments WHERE id = :id AND project_id = :pid");
        $stmt->execute([':id' => $rowId, ':pid' => $projectId]);
        $ok = 'Assignment deleted.';
    } elseif ($action === 'assign') {
        $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?:null,':role_label'=>$role?:null,':notes'=>$notes?:null]);
            $ok = 'Assignment created.';
        }
    }
}

// ── HANDLE NOTIFICATION SEND (from send.php) ──────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_action'])) {
    gp_require_csrf();
    $recipientEmail = trim((string)($_POST['recipient_email'] ?? ''));
    $subjectLine = trim((string)($_POST['subject_line'] ?? ''));
    $bodyText = trim((string)($_POST['body_text'] ?? ''));
    
    if ($recipientEmail === '') $errors[] = 'Recipient email is required.';
    if ($subjectLine === '') $errors[] = 'Subject is required.';

    if (!$errors) {
        $sendError = '';
        $sent = gp_smtp_send($pdo, $recipientEmail, $subjectLine, $bodyText, [], $sendError);
        if ($sent) $ok = 'Email sent successfully.';
        else $errors[] = 'Email send failed: ' . $sendError;
    }
}

$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.id DESC");
$stmt->execute([':pid' => $projectId]);
$assignments = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="page-header">
  <div class="page-header-title">
    <h1>Ανάθεση & Αποστολή</h1>
    <span><?php echo h($project['code'] . ' · ' . $project['title']); ?></span>
  </div>
</div>

<div class="grid-2">
  <!-- Assignment Section -->
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.1rem">🚀 <?php echo $_lang==='el'?'Ανάθεση σε Συνεργείο':'Assign to Crew'; ?></h1></div>
    <?php if ($ok && !isset($_POST['send_action'])): ?><div class="alert-success"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors && !isset($_POST['send_action'])): ?><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; ?>">
      <input type="hidden" name="assign_action" value="assign">
      <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>Role / Task</label><input type="text" name="role"></div>
      </div>
      <div class="form-actions"><button class="btn btn-primary" type="submit">Δημιουργία Ανάθεσης</button></div>
    </form>

    <div style="margin-top:24px">
      <h3 style="font-size:0.9rem">Current Assignments</h3>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Type</th><th>Name</th><th>Date</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($assignments as $a): ?>
              <tr>
                <td><?php echo h($a['assignment_type']); ?></td>
                <td><?php echo h($a['assignment_type']==='employee'?$a['full_name']:$a['company_name']); ?></td>
                <td><?php echo h(gp_date($a['assigned_date'])); ?></td>
                <td>
                  <form method="post" style="display:inline">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="assign_action" value="delete">
                    <input type="hidden" name="row_id" value="<?php echo (int)$a['id']; ?>">
                    <button class="btn btn-sm btn-outline-light" type="submit">✖</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Send Notification Section -->
  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.1rem">📧 <?php echo $_lang==='el'?'Αποστολή Ενημέρωσης':'Send Notification'; ?></h1></div>
    <?php if ($ok && isset($_POST['send_action'])): ?><div class="alert-success"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors && isset($_POST['send_action'])): ?><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-group">
        <label>Recipient Email</label>
        <input type="email" name="recipient_email" required placeholder="Select a crew member below or type here">
      </div>
      <div style="margin-bottom:12px; display:flex; gap:8px; flex-wrap:wrap;">
        <span style="font-size:0.7rem; color:var(--gp-muted); width:100%;">Quick Select:</span>
        <?php foreach ($partners as $p): if($p['email']): ?>
          <button type="button" class="btn btn-xs btn-secondary" onclick="document.getElementsByName('recipient_email')[0].value='<?php echo h($p['email']); ?>'"><?php echo h($p['company_name']); ?></button>
        <?php endif; endforeach; ?>
        <?php foreach ($employees as $e): if($e['email']): ?>
          <button type="button" class="btn btn-xs btn-secondary" onclick="document.getElementsByName('recipient_email')[0].value='<?php echo h($e['email']); ?>'"><?php echo h($e['full_name']); ?></button>
        <?php endif; endforeach; ?>
      </div>
      <div class="form-group">
        <label>Subject</label>
        <input type="text" name="subject_line" value="Project Info: <?php echo h($project['title']); ?>">
      </div>
      <div class="form-group">
        <label>Message</label>
        <textarea name="body_text" style="min-height:200px">Project: <?php echo h($project['title']); ?>&#10;Address: <?php echo h($project['address']); ?>, <?php echo h($project['city']); ?>&#10;Customer: <?php echo h($project['customer_name']); ?>&#10;Phone: <?php echo h($project['customer_phone']); ?></textarea>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit" name="send_action" value="1">Αποστολή Email</button>
      </div>
    </form>
  </div>
</div>

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