<?php
/**
 * /rooms/modules/payments/email_proforma.php
 *
 * Sends proforma PDFs through Microsoft Graph.
 */

require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

require_once __DIR__ . '/../../includes/microsoft_graph_mailer.php';

if (!function_exists('h')) {
    function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

if (!function_exists('ep_table_exists')) {
    function ep_table_exists(PDO $pdo, string $table): bool {
        static $cache = [];
        if (isset($cache[$table])) return $cache[$table];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :t");
            $stmt->execute([':t' => $table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) { return $cache[$table] = false; }
    }
}

if (!function_exists('ep_column_exists')) {
    function ep_column_exists(PDO $pdo, string $table, string $column): bool {
        static $cache = [];
        $key = $table . '.' . $column;
        if (isset($cache[$key])) return $cache[$key];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :t AND column_name = :c");
            $stmt->execute([':t' => $table, ':c' => $column]);
            return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) { return $cache[$key] = false; }
    }
}

if (!function_exists('ep_flash')) {
    function ep_flash(string $type, string $message): void {
        $_SESSION['email_proforma_flash'][] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('ep_get_flash')) {
    function ep_get_flash(): array {
        $rows = $_SESSION['email_proforma_flash'] ?? [];
        unset($_SESSION['email_proforma_flash']);
        return $rows;
    }
}

if (!function_exists('ep_build_pdf_file')) {
    function ep_build_pdf_file(string $absoluteUrl, string $filename): string
    {
        $tmpDir = sys_get_temp_dir() . '/pure_africa_email_docs';
        if (!is_dir($tmpDir)) {
            mkdir($tmpDir, 0775, true);
        }

        $safeName = preg_replace('/[^A-Za-z0-9_.-]/', '_', $filename);
        $target = $tmpDir . '/' . uniqid('doc_', true) . '_' . $safeName;

        $context = stream_context_create([
            'http' => [
                'timeout' => 60,
                'ignore_errors' => true,
                'header' => "Cookie: " . ($_SERVER['HTTP_COOKIE'] ?? '') . "\r\n",
            ],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ],
        ]);

        $data = @file_get_contents($absoluteUrl, false, $context);

        if ($data === false || strlen($data) < 200) {
            throw new RuntimeException('Could not generate or download the PDF attachment.');
        }

        file_put_contents($target, $data);
        return $target;
    }
}

$orderId = (int)($_GET['order_id'] ?? $_POST['order_id'] ?? 0);
$type = strtolower(trim((string)($_GET['type'] ?? $_POST['type'] ?? 'standard')));

$allowedTypes = [
    'standard' => [
        'label' => 'Proforma',
        'file'  => 'proforma_invoice.php',
        'email_type' => 'proforma',
    ],
    'master' => [
        'label' => 'Main Folio Proforma',
        'file'  => 'proforma_master_folio.php',
        'email_type' => 'main_folio_proforma',
    ],
    'room' => [
        'label' => 'Room Proforma',
        'file'  => 'proforma_room_account.php',
        'email_type' => 'room_proforma',
    ],
    'guest' => [
        'label' => 'Guest Folio Proforma',
        'file'  => 'guest_folios.php',
        'email_type' => 'guest_folio_proforma',
    ],
];

if (!isset($allowedTypes[$type])) {
    $type = 'standard';
}

$errors = [];
$order = null;
$guestName = '';
$emailTo = '';
$agentEmail = '';
$guestEmail = '';

if ($orderId <= 0) {
    $errors[] = 'No booking was selected.';
} else {
    try {
        $guestJoin = '';
        $agentJoin = '';
        $guestSelect = "'' AS guest_name, '' AS guest_email";
        $agentSelect = "'' AS agent_email";

        if (ep_table_exists($pdo, 'guests') && ep_column_exists($pdo, 'orders', 'guest_id')) {
            $guestNameExpr = "TRIM(CONCAT(COALESCE(g.firstname,''),' ',COALESCE(g.lastname,'')))";
            $guestEmailExpr = ep_column_exists($pdo, 'guests', 'email') ? 'g.email' : "''";
            $guestJoin = 'LEFT JOIN guests g ON g.id = o.guest_id';
            $guestSelect = "$guestNameExpr AS guest_name, $guestEmailExpr AS guest_email";
        }

        if (ep_table_exists($pdo, 'agents') && ep_column_exists($pdo, 'orders', 'agent_id')) {
            $agentEmailExpr = ep_column_exists($pdo, 'agents', 'email') ? 'a.email' : "''";
            $agentJoin = 'LEFT JOIN agents a ON a.id = o.agent_id';
            $agentSelect = "$agentEmailExpr AS agent_email";
        }

        $orderNoExpr = ep_column_exists($pdo, 'orders', 'order_no') ? 'o.order_no' : 'o.id';
        $checkInExpr = ep_column_exists($pdo, 'orders', 'check_in') ? 'o.check_in' : 'NULL';
        $checkOutExpr = ep_column_exists($pdo, 'orders', 'check_out') ? 'o.check_out' : 'NULL';

        $stmt = $pdo->prepare("
            SELECT
                o.id,
                {$orderNoExpr} AS order_no,
                {$checkInExpr} AS check_in,
                {$checkOutExpr} AS check_out,
                {$guestSelect},
                {$agentSelect}
            FROM orders o
            {$guestJoin}
            {$agentJoin}
            WHERE o.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            throw new RuntimeException('Booking was not found.');
        }

        $guestName = trim((string)($order['guest_name'] ?? ''));
        if ($guestName === '') {
            $guestName = 'Guest';
        }

        $guestEmail = trim((string)($order['guest_email'] ?? ''));
        $agentEmail = trim((string)($order['agent_email'] ?? ''));

        if (filter_var($guestEmail, FILTER_VALIDATE_EMAIL)) {
            $emailTo = $guestEmail;
        } elseif (filter_var($agentEmail, FILTER_VALIDATE_EMAIL)) {
            $emailTo = $agentEmail;
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$proformaFile = $allowedTypes[$type]['file'];
$proformaLabel = $allowedTypes[$type]['label'];
$emailType = $allowedTypes[$type]['email_type'];

$pdfUrl = $proformaFile . '?order_id=' . urlencode((string)$orderId);

$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? '';
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/rooms/modules/payments/email_proforma.php')), '/');
$absolutePdfUrl = ($host !== '') ? ($scheme . '://' . $host . $dir . '/' . $pdfUrl) : $pdfUrl;

$orderNo = $order ? (string)($order['order_no'] ?? ('#' . $orderId)) : ('#' . $orderId);
$subject = $proformaLabel . ' - ' . $orderNo;

$bodyLines = [
    'Dear ' . $guestName . ',',
    '',
    'Please find attached the ' . strtolower($proformaLabel) . ' for booking ' . $orderNo . '.',
];

if (!empty($order['check_in']) || !empty($order['check_out'])) {
    $bodyLines[] = '';
    $bodyLines[] = 'Stay: ' . trim((string)($order['check_in'] ?? '')) . ' to ' . trim((string)($order['check_out'] ?? ''));
}

$bodyLines[] = '';
$bodyLines[] = 'Kind regards,';
$bodyLines[] = defined('MS_GRAPH_SENDER_NAME') ? MS_GRAPH_SENDER_NAME : 'Reservations';

$defaultBody = implode("\n", $bodyLines);
$attachmentName = preg_replace('/[^A-Za-z0-9_-]/', '_', $proformaLabel . '_' . $orderNo) . '.pdf';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) {
            verify_csrf();
        }

        if ($errors) {
            throw new RuntimeException(implode(' ', $errors));
        }

        $to = trim((string)($_POST['email_to'] ?? ''));
        $cc = trim((string)($_POST['email_cc'] ?? ''));
        $bcc = trim((string)($_POST['email_bcc'] ?? ''));
        $subjectPost = trim((string)($_POST['subject'] ?? ''));
        $bodyPost = trim((string)($_POST['body'] ?? ''));

        $pdfPath = ep_build_pdf_file($absolutePdfUrl, $attachmentName);

        try {
            $result = mg_send_pdf_email([
                'to' => $to,
                'cc' => $cc,
                'bcc' => $bcc,
                'subject' => $subjectPost,
                'body' => $bodyPost,
                'attachment_path' => $pdfPath,
                'attachment_name' => $attachmentName,
            ]);

            mg_log_booking_email($pdo, [
                'order_id' => $orderId,
                'email_type' => $emailType,
                'email_to' => implode(', ', $result['to']),
                'email_cc' => implode(', ', $result['cc']),
                'email_bcc' => implode(', ', $result['bcc']),
                'subject' => $subjectPost,
                'body' => $bodyPost,
                'attachment_name' => $attachmentName,
                'provider' => 'microsoft_graph',
                'provider_message_id' => $result['message_id'],
                'status' => 'sent',
                'sent_by' => mg_current_user_id(),
            ]);

            ep_flash('success', $proformaLabel . ' sent successfully through Microsoft 365.');
        } catch (Throwable $sendError) {
            mg_log_booking_email($pdo, [
                'order_id' => $orderId,
                'email_type' => $emailType,
                'email_to' => $to,
                'email_cc' => $cc,
                'email_bcc' => $bcc,
                'subject' => $subjectPost,
                'body' => $bodyPost,
                'attachment_name' => $attachmentName,
                'provider' => 'microsoft_graph',
                'status' => 'failed',
                'error_message' => $sendError->getMessage(),
                'sent_by' => mg_current_user_id(),
            ]);
            throw $sendError;
        } finally {
            if (!empty($pdfPath) && is_file($pdfPath)) {
                @unlink($pdfPath);
            }
        }

        header('Location: email_proforma.php?order_id=' . $orderId . '&type=' . urlencode($type));
        exit;
    } catch (Throwable $e) {
        ep_flash('danger', $e->getMessage());
        header('Location: email_proforma.php?order_id=' . $orderId . '&type=' . urlencode($type));
        exit;
    }
}

$flashes = ep_get_flash();

$pageTitle = 'Email Proforma';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="card panel-card mx-auto email-proforma-card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h5 class="mb-0"><i class="bi bi-envelope-paper me-2"></i>Email <?php echo h($proformaLabel); ?></h5>
            <div class="small text-muted">Booking <?php echo h($orderNo); ?></div>
        </div>
        <a href="../calendar/calendar.php" class="btn btn-sm btn-outline-secondary">Back to Calendar</a>
    </div>

    <div class="card-body">
        <?php foreach ($flashes as $flash): ?>
            <div class="alert alert-<?php echo h($flash['type']); ?>"><?php echo h($flash['message']); ?></div>
        <?php endforeach; ?>

        <?php if ($errors): ?>
            <div class="alert alert-danger">
                <strong>Could not continue:</strong>
                <ul class="mb-0">
                    <?php foreach ($errors as $err): ?>
                        <li><?php echo h($err); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php else: ?>
            <form method="post" onsubmit="return confirm('Send this email with PDF attachment through Microsoft 365?');">
                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">
                <input type="hidden" name="type" value="<?php echo h($type); ?>">

                <div class="alert alert-info">
                    This sends from <strong><?php echo h(defined('MS_GRAPH_SENDER_EMAIL') ? MS_GRAPH_SENDER_EMAIL : 'configured mailbox'); ?></strong>
                    using Microsoft Graph, with the PDF attached automatically.
                </div>

                <div class="row g-3 mb-3">
                    <div class="col-md-8">
                        <label class="form-label fw-bold">To</label>
                        <input type="text" name="email_to" class="form-control" value="<?php echo h($emailTo); ?>" placeholder="guest@email.com, agent@email.com" required>
                        <div class="small text-muted">
                            Guest email: <?php echo h($guestEmail ?: 'none'); ?> |
                            Agent email: <?php echo h($agentEmail ?: 'none'); ?>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label fw-bold">CC</label>
                        <input type="text" name="email_cc" class="form-control" value="">
                    </div>

                    <div class="col-md-12">
                        <label class="form-label fw-bold">BCC</label>
                        <input type="text" name="email_bcc" class="form-control" value="">
                    </div>

                    <div class="col-md-12">
                        <label class="form-label fw-bold">Subject</label>
                        <input type="text" name="subject" class="form-control" value="<?php echo h($subject); ?>" required>
                    </div>

                    <div class="col-md-12">
                        <label class="form-label fw-bold">Message</label>
                        <textarea name="body" class="form-control" rows="8" required><?php echo h($defaultBody); ?></textarea>
                    </div>
                </div>

                <div class="border rounded p-3 bg-light mb-3">
                    <div class="fw-bold mb-1">Attachment</div>
                    <div><?php echo h($attachmentName); ?></div>
                    <div class="small text-muted">Generated from: <?php echo h($pdfUrl); ?></div>
                    <a class="btn btn-sm btn-outline-primary mt-2" href="<?php echo h($pdfUrl); ?>" target="_blank" rel="noopener">
                        Preview PDF
                    </a>
                </div>

                <div class="d-flex flex-wrap gap-2">
                    <button class="btn btn-primary">
                        <i class="bi bi-send me-2"></i>Send Email
                    </button>
                    <a href="<?php echo h($pdfUrl); ?>" target="_blank" rel="noopener" class="btn btn-outline-secondary">
                        <i class="bi bi-file-earmark-pdf me-2"></i>Open PDF
                    </a>
                </div>
            </form>
        <?php endif; ?>
    </div>
</div>

<style>
.email-proforma-card{
    max-width:900px;
}
.email-proforma-card .card-header{
    padding:12px 14px;
}
.email-proforma-card .card-body{
    padding:14px;
}
.email-proforma-card textarea{
    min-height:175px;
}
</style>

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