<?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();
$page_title = 'Send project to crew';

$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.');

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

$stmt = $pdo->prepare("SELECT file_name, file_path, file_type, notes, uploaded_at FROM project_files WHERE project_id = :pid ORDER BY uploaded_at DESC, id DESC");
$stmt->execute([':pid' => $projectId]);
$projectFiles = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT item_name, category, quantity, notes FROM project_equipment WHERE project_id = :pid ORDER BY id ASC");
$stmt->execute([':pid' => $projectId]);
$equipmentRows = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT title, due_date, status, notes FROM project_tasks WHERE project_id = :pid ORDER BY due_date ASC, id ASC");
$stmt->execute([':pid' => $projectId]);
$taskRows = $stmt->fetchAll();

$mapsUrl = '';
$addressParts = array_filter([(string)($project['address'] ?? ''), (string)($project['city'] ?? '')]);
$addressQuery = trim(implode(', ', $addressParts));
if (!empty($project['latitude']) && !empty($project['longitude'])) {
    $mapsUrl = 'https://www.google.com/maps?q=' . rawurlencode($project['latitude'] . ',' . $project['longitude']);
} elseif ($addressQuery !== '') {
    $mapsUrl = 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode($addressQuery);
}

function gp_e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function gp_build_project_email_body(array $project, string $mapsUrl, array $equipmentRows, array $taskRows, array $projectFiles): string
{
    $customerName = (string)($project['customer_name'] ?? '');
    $customerContact = (string)($project['contact_person'] ?? '');
    $customerPhone = (string)($project['customer_phone'] ?? '');
    $customerEmail = (string)($project['customer_email'] ?? '');
    $projectNotes = nl2br(gp_e((string)($project['notes'] ?? '')));
    $address = gp_e((string)($project['address'] ?? ''));
    $city = gp_e((string)($project['city'] ?? ''));

    $equipmentHtml = '';
    if (!$equipmentRows) {
        $equipmentHtml = '<li>None</li>';
    } else {
        foreach ($equipmentRows as $r) {
            $parts = [];
            $parts[] = gp_e((string)$r['item_name']);
            $parts[] = 'qty: ' . gp_e((string)$r['quantity']);
            if (!empty($r['category'])) $parts[] = gp_e((string)$r['category']);
            if (!empty($r['notes'])) $parts[] = gp_e((string)$r['notes']);
            $equipmentHtml .= '<li>' . implode(' · ', $parts) . '</li>';
        }
    }

    $tasksHtml = '';
    if (!$taskRows) {
        $tasksHtml = '<li>None</li>';
    } else {
        foreach ($taskRows as $r) {
            $parts = [];
            $parts[] = gp_e((string)$r['title']);
            $parts[] = 'status: ' . gp_e((string)$r['status']);
            if (!empty($r['due_date'])) $parts[] = 'due: ' . gp_e((string)$r['due_date']);
            if (!empty($r['notes'])) $parts[] = gp_e((string)$r['notes']);
            $tasksHtml .= '<li>' . implode(' · ', $parts) . '</li>';
        }
    }

    $filesHtml = '';
    if (!$projectFiles) {
        $filesHtml = '<li>No attached files in project</li>';
    } else {
        foreach ($projectFiles as $f) {
            $filesHtml .= '<li>' . gp_e((string)$f['file_name']) . '</li>';
        }
    }

    $mapButton = '';
    if ($mapsUrl !== '') {
        $mapButton = '<p style="margin:16px 0 0 0"><a href="' . gp_e($mapsUrl) . '" style="display:inline-block;background:#2563eb;color:#ffffff;text-decoration:none;padding:10px 14px;border-radius:10px;font-weight:700">Open map</a></p>';
    }

    return '<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Project Assignment</title>
</head>
<body style="margin:0;padding:24px;background:#f3f6fb;font-family:Arial,Helvetica,sans-serif;color:#0f172a;line-height:1.6;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:820px;margin:0 auto;background:#ffffff;border:1px solid #e5e7eb;border-radius:18px;overflow:hidden;">
    <tr>
      <td style="padding:24px 28px;background:linear-gradient(135deg,#2563eb,#0f172a);color:#ffffff;">
        <div style="font-size:13px;opacity:.9;letter-spacing:.08em;text-transform:uppercase;">GoPools CRM</div>
        <h1 style="margin:8px 0 0 0;font-size:28px;line-height:1.2;">Project Assignment</h1>
      </td>
    </tr>
    <tr>
      <td style="padding:24px 28px;">
        <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;">
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Project</td><td style="padding:8px 0;">' . gp_e((string)($project['title'] ?? '')) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Code</td><td style="padding:8px 0;">' . gp_e((string)($project['code'] ?? '')) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Status</td><td style="padding:8px 0;">' . gp_e((string)($project['status'] ?? '')) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Customer</td><td style="padding:8px 0;">' . gp_e($customerName) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Contact</td><td style="padding:8px 0;">' . gp_e($customerContact) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Phone</td><td style="padding:8px 0;">' . gp_e($customerPhone) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Email</td><td style="padding:8px 0;">' . gp_e($customerEmail) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Address</td><td style="padding:8px 0;">' . $address . ($city !== '' ? ' · ' . $city : '') . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Start date</td><td style="padding:8px 0;">' . gp_e((string)($project['start_date'] ?? '')) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Planned end</td><td style="padding:8px 0;">' . gp_e((string)($project['end_date_planned'] ?? '')) . '</td></tr>
          <tr><td style="padding:8px 0;width:180px;color:#475569;font-weight:700;">Budget</td><td style="padding:8px 0;">' . gp_e((string)($project['budget'] ?? '')) . '</td></tr>
        </table>
        ' . $mapButton . '
      </td>
    </tr>
    <tr>
      <td style="padding:0 28px 24px 28px;">
        <div style="border:1px solid #e5e7eb;border-radius:14px;padding:16px;background:#f8fafc;">
          <div style="font-weight:800;margin-bottom:8px;">Project notes</div>
          <div>' . ($projectNotes !== '' ? $projectNotes : '<span style="color:#64748b">No project notes</span>') . '</div>
        </div>
      </td>
    </tr>
    <tr>
      <td style="padding:0 28px 24px 28px;">
        <div style="font-weight:800;margin-bottom:8px;">Equipment</div>
        <ul style="margin:0;padding-left:20px;">' . $equipmentHtml . '</ul>
      </td>
    </tr>
    <tr>
      <td style="padding:0 28px 24px 28px;">
        <div style="font-weight:800;margin-bottom:8px;">Tasks</div>
        <ul style="margin:0;padding-left:20px;">' . $tasksHtml . '</ul>
      </td>
    </tr>
    <tr>
      <td style="padding:0 28px 28px 28px;">
        <div style="font-weight:800;margin-bottom:8px;">Files</div>
        <ul style="margin:0;padding-left:20px;">' . $filesHtml . '</ul>
      </td>
    </tr>
  </table>
</body>
</html>';
}

$recipientType = trim((string)($_POST['recipient_type'] ?? 'partner'));
$selectedPartnerId = (int)($_POST['external_partner_id'] ?? 0);
$selectedEmployeeId = (int)($_POST['employee_id'] ?? 0);
$recipientEmail = trim((string)($_POST['recipient_email'] ?? ''));
$recipientName = trim((string)($_POST['recipient_name'] ?? ''));
$subjectLine = trim((string)($_POST['subject_line'] ?? ''));
$bodyText = trim((string)($_POST['body_text'] ?? ''));
$includeFiles = isset($_POST['include_files']) ? 1 : 0;
$ok = '';
$errors = [];

if ($recipientType === 'partner' && $selectedPartnerId > 0 && ($recipientEmail === '' || $recipientName === '')) {
    foreach ($partners as $p) {
        if ((int)$p['id'] === $selectedPartnerId) {
            if ($recipientEmail === '') $recipientEmail = (string)($p['email'] ?? '');
            if ($recipientName === '') $recipientName = trim((string)($p['company_name'] ?? '') . ' ' . (string)($p['contact_person'] ?? ''));
            break;
        }
    }
}
if ($recipientType === 'employee' && $selectedEmployeeId > 0 && ($recipientEmail === '' || $recipientName === '')) {
    foreach ($employees as $e) {
        if ((int)$e['id'] === $selectedEmployeeId) {
            if ($recipientEmail === '') $recipientEmail = (string)($e['email'] ?? '');
            if ($recipientName === '') $recipientName = trim((string)($e['full_name'] ?? ''));
            break;
        }
    }
}

if ($subjectLine === '') $subjectLine = 'Project Assignment - ' . (string)$project['title'];
if ($bodyText === '') $bodyText = gp_build_project_email_body($project, $mapsUrl, $equipmentRows, $taskRows, $projectFiles);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($recipientEmail === '') $errors[] = 'Recipient email is required.';
    if ($subjectLine === '') $errors[] = 'Subject is required.';
    if ($bodyText === '') $errors[] = 'Body is required.';

    if (!$errors) {
        $attachments = [];
        if ($includeFiles) {
            foreach ($projectFiles as $f) {
                $webPath = (string)$f['file_path'];
                $absPath = $_SERVER['DOCUMENT_ROOT'] . $webPath;
                if (is_file($absPath)) {
                    $attachments[] = ['path' => $absPath, 'name' => (string)$f['file_name']];
                }
            }
        }

        $sendError = '';
        $sent = gp_smtp_send($pdo, $recipientEmail, $subjectLine, $bodyText, $attachments, $sendError);

        $stmt = $pdo->prepare("INSERT INTO project_email_log (project_id, recipient_email, recipient_name, subject_line, body_text, status, error_message) VALUES (:project_id, :recipient_email, :recipient_name, :subject_line, :body_text, :status, :error_message)");
        $stmt->execute([
            ':project_id' => $projectId,
            ':recipient_email' => $recipientEmail,
            ':recipient_name' => $recipientName !== '' ? $recipientName : null,
            ':subject_line' => $subjectLine,
            ':body_text' => $bodyText,
            ':status' => $sent ? 'sent' : 'failed',
            ':error_message' => $sent ? null : $sendError,
        ]);

        if ($sent) $ok = 'Email sent successfully.';
        else $errors[] = 'Email send failed: ' . $sendError;
    }
}

$stmt = $pdo->prepare("SELECT * FROM project_email_log WHERE project_id = :pid ORDER BY created_at DESC, id DESC LIMIT 20");
$stmt->execute([':pid' => $projectId]);
$emailLog = $stmt->fetchAll();

include __DIR__ . '/../includes/header.php';
?>
<div class="page-header">
  <div class="page-header-title">
    <h1>Send project to crew</h1>
    <span><?php echo h($project['code'] . ' · ' . $project['title']); ?></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:#bbf7d0;border-color:rgba(22,163,74,.35)"><?php echo h($ok); ?></div><?php endif; ?>
    <?php if ($errors): ?><div class="alert-danger"><?php echo h(implode(' ', $errors)); ?></div><?php endif; ?>

    <div class="page-header-title">
      <h1 style="font-size:1.05rem">Email form</h1>
      <span>Send project details to partner, employee, or custom email</span>
    </div>

    <form method="post">
      <input type="hidden" name="project_id" value="<?php echo (int)$projectId; ?>">
      <div class="form-grid">
        <div class="form-group"><label>Recipient type</label><select name="recipient_type" onchange="this.form.submit()"><option value="partner" <?php echo $recipientType === 'partner' ? 'selected' : ''; ?>>Partner</option><option value="employee" <?php echo $recipientType === 'employee' ? 'selected' : ''; ?>>Employee</option><option value="custom" <?php echo $recipientType === 'custom' ? 'selected' : ''; ?>>Custom email</option></select></div>
        <div class="form-group"><label>Partner</label><select name="external_partner_id" onchange="this.form.submit()"><option value="0">Select...</option><?php foreach ($partners as $p): ?><option value="<?php echo (int)$p['id']; ?>" <?php echo $selectedPartnerId === (int)$p['id'] ? 'selected' : ''; ?>><?php echo h($p['company_name'] . ' · ' . $p['contact_person'] . ' · ' . $p['specialty']); ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label>Employee</label><select name="employee_id" onchange="this.form.submit()"><option value="0">Select...</option><?php foreach ($employees as $e): ?><option value="<?php echo (int)$e['id']; ?>" <?php echo $selectedEmployeeId === (int)$e['id'] ? 'selected' : ''; ?>><?php echo h($e['full_name'] . ' · ' . $e['role_title']); ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label>Recipient name</label><input type="text" name="recipient_name" value="<?php echo h($recipientName); ?>"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Recipient email</label><input type="email" name="recipient_email" value="<?php echo h($recipientEmail); ?>"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Subject</label><input type="text" name="subject_line" value="<?php echo h($subjectLine); ?>"></div>
        <div class="form-group" style="grid-column:1/-1"><label>Body (HTML supported)</label><textarea name="body_text" style="min-height:340px"><?php echo h($bodyText); ?></textarea></div>
        <div class="form-group"><label>Include project files as attachments</label><div><input type="checkbox" name="include_files" <?php echo $includeFiles ? 'checked' : ''; ?>></div></div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Send email</button>
        <a class="btn btn-secondary" href="/public/settings/smtp.php">SMTP settings</a>
        <?php if ($mapsUrl): ?><a class="btn btn-secondary" href="<?php echo h($mapsUrl); ?>" target="_blank" rel="noopener">Open map</a><?php endif; ?>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem">Project summary</h1><span>What will be sent</span></div>
    <p><strong>Customer:</strong> <?php echo h($project['customer_name']); ?></p>
    <p><strong>Customer phone:</strong> <?php echo h($project['customer_phone']); ?></p>
    <p><strong>Address:</strong> <?php echo h($project['address']); ?></p>
    <p><strong>City:</strong> <?php echo h($project['city']); ?></p>
    <p><strong>Start date:</strong> <?php echo h($project['start_date']); ?></p>
    <p><strong>Planned end:</strong> <?php echo h($project['end_date_planned']); ?></p>

    <div class="page-header-title" style="margin-top:12px"><h1 style="font-size:1rem">Project files</h1></div>
    <?php if (!$projectFiles): ?><p class="small">No files attached to this project.</p><?php else: ?><ul><?php foreach ($projectFiles as $f): ?><li><?php echo h($f['file_name']); ?></li><?php endforeach; ?></ul><?php endif; ?>

    <div class="page-header-title" style="margin-top:12px"><h1 style="font-size:1rem">Recent email log</h1></div>
    <?php if (!$emailLog): ?><p class="small">No email history yet.</p><?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th>Date</th><th>To</th><th>Status</th></tr></thead>
          <tbody><?php foreach ($emailLog as $r): ?><tr><td><?php echo h($r['created_at']); ?></td><td><?php echo h($r['recipient_email']); ?></td><td><?php echo h($r['status']); ?></td></tr><?php endforeach; ?></tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>
</div>

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