<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/access_guards.php';
require_once __DIR__ . '/helpers.php';
auth_require_login();
$pdo = crm_pdo();
gp_require_staff_access($pdo);

$id = (int)($_GET['id'] ?? 0);
$action = trim((string)($_GET['action'] ?? ''));
if ($id <= 0 || $action === '') die('Missing action.');

$stmt = $pdo->prepare("SELECT * FROM inbox_emails WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $id]);
$email = $stmt->fetch();
if (!$email) die('Inbox email not found.');

$stmt = $pdo->prepare("SELECT * FROM inbox_attachments WHERE inbox_email_id = :id ORDER BY id ASC");
$stmt->execute([':id' => $id]);
$attachments = $stmt->fetchAll();

$extract = inbox_extract_lines((string)$email['subject'], (string)$email['body_text']);

if ($action === 'archive') {
    $stmt = $pdo->prepare("UPDATE inbox_emails SET status = 'archived' WHERE id = :id");
    $stmt->execute([':id' => $id]);
    redirect('/gopools/public/inbox/show.php?id=' . $id);
}

if ($action === 'create_customer') {
    $matched = inbox_find_customer_from_signature($pdo, $extract);
    if ($matched) {
        $customerId = (int)$matched['id'];
    } else {
        $customerName = trim((string)$extract['signature_company']);
        if ($customerName === '') $customerName = trim((string)$extract['signature_name']);
        if ($customerName === '') $customerName = trim((string)($email['from_name'] ?? ''));
        if ($customerName === '') $customerName = trim((string)($email['from_email'] ?? 'Unknown customer'));

        $contactPerson = trim((string)$extract['signature_name']);
        if ($contactPerson === '') $contactPerson = trim((string)($email['from_name'] ?? ''));

        $customerEmail = trim((string)$extract['signature_email']);
        if ($customerEmail === '') $customerEmail = trim((string)($email['from_email'] ?? ''));

        $customerPhone = trim((string)$extract['signature_phone']);
        if ($customerPhone === '') $customerPhone = trim((string)($extract['phone'] ?? ''));

        $stmt = $pdo->prepare("
            INSERT INTO customers (name, contact_person, phone, email, notes, active)
            VALUES (:name, :contact_person, :phone, :email, :notes, 1)
        ");
        $stmt->execute([
            ':name' => $customerName,
            ':contact_person' => $contactPerson !== '' ? $contactPerson : null,
            ':phone' => $customerPhone !== '' ? $customerPhone : null,
            ':email' => $customerEmail !== '' ? $customerEmail : null,
            ':notes' => 'Created from inbox email #' . $id . ' using signature matching',
        ]);
        $customerId = (int)$pdo->lastInsertId();
    }

    $stmt = $pdo->prepare("UPDATE inbox_emails SET linked_customer_id = :cid, status = 'approved' WHERE id = :id");
    $stmt->execute([':cid' => $customerId, ':id' => $id]);

    redirect('/gopools/public/customers/edit.php?id=' . $customerId);
}

if ($action === 'create_project') {
    $matched = inbox_find_customer_from_signature($pdo, $extract);
    $customerId = $matched ? (int)$matched['id'] : (int)($email['linked_customer_id'] ?? 0);

    if ($customerId <= 0) {
        $customerName = trim((string)$extract['signature_company']);
        if ($customerName === '') $customerName = trim((string)$extract['signature_name']);
        if ($customerName === '') $customerName = trim((string)($email['from_name'] ?? ''));
        if ($customerName === '') $customerName = trim((string)($email['from_email'] ?? 'Unknown customer'));

        $contactPerson = trim((string)$extract['signature_name']);
        if ($contactPerson === '') $contactPerson = trim((string)($email['from_name'] ?? ''));

        $customerEmail = trim((string)$extract['signature_email']);
        if ($customerEmail === '') $customerEmail = trim((string)($email['from_email'] ?? ''));

        $customerPhone = trim((string)$extract['signature_phone']);
        if ($customerPhone === '') $customerPhone = trim((string)($extract['phone'] ?? ''));

        $stmt = $pdo->prepare("
            INSERT INTO customers (name, contact_person, phone, email, notes, active)
            VALUES (:name, :contact_person, :phone, :email, :notes, 1)
        ");
        $stmt->execute([
            ':name' => $customerName,
            ':contact_person' => $contactPerson !== '' ? $contactPerson : null,
            ':phone' => $customerPhone !== '' ? $customerPhone : null,
            ':email' => $customerEmail !== '' ? $customerEmail : null,
            ':notes' => 'Auto-created from inbox email #' . $id . ' using signature matching',
        ]);
        $customerId = (int)$pdo->lastInsertId();
    }

    $catId = null;
    if ($extract['project_type'] !== '') {
        $stmt = $pdo->prepare("SELECT id FROM project_categories WHERE name = :n LIMIT 1");
        $stmt->execute([':n' => $extract['project_type']]);
        $catId = $stmt->fetchColumn() ?: null;
    }

    $title = trim((string)$email['subject']);
    if ($title === '') $title = 'Inbox project #' . $id;

    $budget = null;
    if ($extract['amount'] !== '') {
        $budget = (float)str_replace([','], ['.'], preg_replace('/[^\d\.,]/', '', $extract['amount']));
    }

    $stmt = $pdo->prepare("
        INSERT INTO projects (code, title, customer_id, category_id, status, budget, notes)
        VALUES (:code, :title, :customer_id, :category_id, 'planned', :budget, :notes)
    ");
    $stmt->execute([
        ':code' => 'PRJ-' . date('Ymd-His'),
        ':title' => $title,
        ':customer_id' => $customerId,
        ':category_id' => $catId,
        ':budget' => $budget,
        ':notes' => 'Created from inbox email #' . $id . ' using signature matching',
    ]);
    $projectId = (int)$pdo->lastInsertId();

    foreach ($attachments as $a) {
        $stmt = $pdo->prepare("
            INSERT INTO project_files (project_id, file_name, file_path, file_type, notes)
            VALUES (:pid, :file_name, :file_path, :file_type, :notes)
        ");
        $stmt->execute([
            ':pid' => $projectId,
            ':file_name' => $a['file_name'],
            ':file_path' => $a['file_path'],
            ':file_type' => $a['mime_type'] ?: null,
            ':notes' => 'Copied from inbox email #' . $id,
        ]);
    }

    $stmt = $pdo->prepare("
        UPDATE inbox_emails
        SET linked_customer_id = :cid,
            linked_project_id = :pid,
            status = 'approved',
            suggested_type = 'project'
        WHERE id = :id
    ");
    $stmt->execute([
        ':cid' => $customerId,
        ':pid' => $projectId,
        ':id' => $id,
    ]);

    if ($extract['deposit'] !== '') {
        $deposit = (float)str_replace([','], ['.'], preg_replace('/[^\d\.,]/', '', $extract['deposit']));
        if ($deposit > 0) {
            $stmt = $pdo->prepare("
                INSERT INTO project_payments (project_id, payment_type, amount, payment_date, notes)
                VALUES (:pid, 'deposit', :amt, CURDATE(), :notes)
            ");
            $stmt->execute([
                ':pid' => $projectId,
                ':amt' => $deposit,
                ':notes' => 'Auto-created deposit from inbox email #' . $id,
            ]);
        }
    }

    redirect('/gopools/public/projects/edit.php?id=' . $projectId);
}

die('Unsupported action.');
