<?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 = '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 = str_replace(["\r\n", "\r"], "\n", (string)($project['notes'] ?? ''));
    $address = (string)($project['address'] ?? '');
    $city = (string)($project['city'] ?? '');

    $text = "Project Assignment\n";
    $text .= "----------------------------------------\n";
    $text .= "Project: " . (string)($project['title'] ?? '') . "\n";
    $text .= "Code: " . (string)($project['code'] ?? '') . "\n";
    $text .= "Status: " . (string)($project['status'] ?? '') . "\n";
    $text .= "Customer: $customerName\n";
    $text .= "Contact: $customerContact\n";
    $text .= "Phone: $customerPhone\n";
    if ($customerEmail) $text .= "Email: $customerEmail\n";
    $text .= "Address: $address" . ($city !== '' ? " - $city" : "") . "\n";
    $text .= "Start date: " . (string)($project['start_date'] ?? '') . "\n";
    $text .= "Planned end: " . (string)($project['end_date_planned'] ?? '') . "\n";
    $text .= "Budget: " . (string)($project['budget'] ?? '') . "\n";
    
    if ($mapsUrl !== '') {
        $text .= "\nGoogle Maps: $mapsUrl\n";
    }

    if ($projectNotes !== '') {
        $text .= "\n[ S?�e??se?? ????? ]\n$projectNotes\n";
    }

    $text .= "\n[ Equipment ]\n";
    if (!$equipmentRows) {
        $text .= "- None\n";
    } else {
        foreach ($equipmentRows as $r) {
            $parts = [(string)$r['item_name'], 'qty: ' . (string)$r['quantity']];
            if (!empty($r['category'])) $parts[] = (string)$r['category'];
            if (!empty($r['notes'])) $parts[] = (string)$r['notes'];
            $text .= "- " . implode(' | ', $parts) . "\n";
        }
    }

    $text .= "\n[ Tasks ]\n";
    if (!$taskRows) {
        $text .= "- None\n";
    } else {
        foreach ($taskRows as $r) {
            $parts = [(string)$r['title'], 'status: ' . (string)$r['status']];
            if (!empty($r['due_date'])) $parts[] = 'due: ' . (string)$r['due_date'];
            if (!empty($r['notes'])) $parts[] = (string)$r['notes'];
            $text .= "- " . implode(' | ', $parts) . "\n";
        }
    }

    $text .= "\n[ Files ]\n";
    if (!$projectFiles) {
        $text .= "- No attached files\n";
    } else {
        foreach ($projectFiles as $f) {
            $text .= "- " . (string)$f['file_name'] . "\n";
        }
    }

    return trim($text);
}

$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 = ($_lang==='el'?'Ανάθεση Έργου - ':'Project Assignment - ') . (string)$project['title'];
if ($bodyText === '') $bodyText = gp_build_project_email_body($project, $mapsUrl, $equipmentRows, $taskRows, $projectFiles);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['send_action'])) {
    gp_require_csrf();
    if ($recipientEmail === '') $errors[] = $_lang==='el'?'Το email παραλήπτη είναι υποχρεωτικό.':'Recipient email is required.';
    if ($subjectLine === '') $errors[] = $_lang==='el'?'Το θέμα είναι υποχρεωτικό.':'Subject is required.';
    if ($bodyText === '') $errors[] = $_lang==='el'?'Το κείμενο email είναι υποχρεωτικό.':'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 = $_lang==='el'?'Το email στάλθηκε επιτυχώς.':'Email sent successfully.';
        else $errors[] = ($_lang==='el'?'Αποτυχία αποστολής: ':'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';
?>
<?php gp_render_project_menu($pdo, $projectId); ?>

<div class="page-header">
  <div class="page-header-title">
    <h1><?php echo gp_tr($pdo,'send_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="/gopools/public/projects/edit.php?id=<?php echo (int)$projectId; ?>"><?php echo gp_tr($pdo,'back'); ?></a>
  </div>
</div>

<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"><?php echo $_lang==='el'?'Φόρμα Αποστολής':'Email form'; ?></h1>
      <span><?php echo $_lang==='el'?'Αποστολή στοιχείων έργου σε συνεργάτη ή υπάλληλο':'Send project details to partner, employee, or custom email'; ?></span>
    </div>

    <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><?php echo $_lang==='el'?'Τύπος Παραλήπτη':'Recipient type'; ?></label><select name="recipient_type" onchange="this.form.submit()"><option value="partner" <?php echo $recipientType === 'partner' ? 'selected' : ''; ?>><?php echo $_lang==='el'?'Συνεργάτης':'Partner'; ?></option><option value="employee" <?php echo $recipientType === 'employee' ? 'selected' : ''; ?>><?php echo $_lang==='el'?'Υπάλληλος':'Employee'; ?></option><option value="custom" <?php echo $recipientType === 'custom' ? 'selected' : ''; ?>><?php echo $_lang==='el'?'Άλλο email':'Custom email'; ?></option></select></div>
        <div class="form-group"><label><?php echo $_lang==='el'?'Συνεργάτης':'Partner'; ?></label><select name="external_partner_id" onchange="this.form.submit()"><option value="0"><?php echo gp_tr($pdo,'select_empty'); ?></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><?php echo $_lang==='el'?'Υπάλληλος':'Employee'; ?></label><select name="employee_id" onchange="this.form.submit()"><option value="0"><?php echo gp_tr($pdo,'select_empty'); ?></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><?php echo $_lang==='el'?'Όνομα Παραλήπτη':'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>Email <?php echo $_lang==='el'?'Παραλήπτη':'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><?php echo $_lang==='el'?'Θέμα':'Subject'; ?></label><input type="text" name="subject_line" value="<?php echo h($subjectLine); ?>"></div>
        <div class="form-group" style="grid-column:1/-1"><label><?php echo $_lang==='el'?'Κείμενο Email':'Body (HTML supported)'; ?></label><textarea name="body_text" style="min-height:340px"><?php echo h($bodyText); ?></textarea></div>
        <div class="form-group"><label><?php echo $_lang==='el'?'Συμπερίληψη αρχείων έργου':'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" name="send_action" value="1"><?php echo $_lang==='el'?'Αποστολή':'Send email'; ?></button>
        <a class="btn btn-secondary" href="/gopools/public/settings/smtp.php"><?php echo $_lang==='el'?'Ρυθμίσεις SMTP':'SMTP settings'; ?></a>
        <?php if ($mapsUrl): ?><a class="btn btn-secondary" href="<?php echo h($mapsUrl); ?>" target="_blank" rel="noopener"><?php echo $_lang==='el'?'Άνοιγμα χάρτη':'Open map'; ?></a><?php endif; ?>
      </div>
    </form>
  </div>

  <div class="card">
    <div class="page-header-title"><h1 style="font-size:1.05rem"><?php echo $_lang==='el'?'Σύνοψη έργου':'Project summary'; ?></h1><span><?php echo $_lang==='el'?'Δεδομένα που θα σταλούν':'What will be sent'; ?></span></div>
    <p><strong><?php echo gp_tr($pdo,'customer'); ?>:</strong> <?php echo h($project['customer_name']); ?></p>
    <p><strong><?php echo gp_tr($pdo,'phone'); ?>:</strong> <?php echo h($project['customer_phone']); ?></p>
    <p><strong><?php echo $_lang==='el'?'Διεύθυνση':'Address'; ?>:</strong> <?php echo h($project['address']); ?></p>
    <p><strong><?php echo gp_tr($pdo,'city'); ?>:</strong> <?php echo h($project['city']); ?></p>
    <p><strong><?php echo gp_tr($pdo,'start_date'); ?>:</strong> <?php echo h($project['start_date']); ?></p>
    <p><strong><?php echo gp_tr($pdo,'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"><?php echo $_lang==='el'?'Αρχεία Έργου':'Project files'; ?></h1></div>
    <?php if (!$projectFiles): ?><p class="small"><?php echo $_lang==='el'?'Δεν υπάρχουν αρχεία.':'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"><?php echo $_lang==='el'?'Ιστορικό Email':'Recent email log'; ?></h1></div>
    <?php if (!$emailLog): ?><p class="small"><?php echo $_lang==='el'?'Δεν υπάρχει ιστορικό.':'No email history yet.'; ?></p><?php else: ?>
      <div class="table-responsive">
        <table class="table">
          <thead><tr><th><?php echo gp_tr($pdo,'date'); ?></th><th><?php echo $_lang==='el'?'Παραλήπτης':'To'; ?></th><th><?php echo gp_tr($pdo,'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'; ?>
