<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../lib/auth.php';
require_once __DIR__ . '/../lib/csrf.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

requireLogin();

$pageTitle = 'Compose Email';
$siteName  = 'Crop Monitor';

$user     = getCurrentUser() ?? [];
$fullname = $user['fullname'] ?? '';
$email    = $user['email']    ?? '';

$errors  = [];
$success = false;

// Email sending requires PHPMailer — currently a stub
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send'])) {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid CSRF token.';
    } else {
        // TODO: configure PHPMailer / SMTP and send email
        $errors[] = 'Email sending is not yet configured. Please set up SMTP in lib/mailer.php.';
    }
}

$h = fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

include __DIR__ . '/../layouts/header.php';
include __DIR__ . '/../layouts/navbar.php';
?>

<div id="layoutSidenav">
    <div id="layoutSidenav_nav">
        <?php include __DIR__ . '/../layouts/sidebar.php'; ?>
    </div>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">
                <h1 class="mt-4"><?= $h($pageTitle) ?></h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="/dashboard/dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Compose Email</li>
                </ol>

                <?php foreach ($errors as $err): ?>
                    <div class="alert alert-danger"><?= $h($err) ?></div>
                <?php endforeach; ?>
                <?php if ($success): ?>
                    <div class="alert alert-success">Email sent successfully.</div>
                <?php endif; ?>

                <div class="row">
                    <div class="col-md-8">
                        <form class="needs-validation" id="email-form" method="post"
                              action="" enctype="multipart/form-data" novalidate>
                            <input type="hidden" name="csrf_token" value="<?= $h(generateCsrfToken()) ?>">

                            <!-- From -->
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="far fa-paper-plane"></i></span>
                                <input type="text" class="form-control fw-bold"
                                       value="<?= $h($fullname) ?> <<?= $h($email) ?>>" readonly>
                            </div>
                            <input type="hidden" name="emailFrom"     value="<?= $h($email) ?>">
                            <input type="hidden" name="emailFromName" value="<?= $h($fullname) ?>">
                            <input type="hidden" name="emailReply"    value="<?= $h($email) ?>">
                            <input type="hidden" name="emailReplyName" value="<?= $h($fullname) ?>">

                            <!-- To -->
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="fas fa-envelope-open"></i></span>
                                <input type="email" class="form-control" name="emailAddress"
                                       placeholder="To" required>
                                <div class="invalid-feedback">Please provide a valid email address.</div>
                            </div>

                            <!-- CC -->
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="far fa-envelope-open"></i></span>
                                <input type="email" class="form-control" name="carboncopy" placeholder="CC">
                            </div>

                            <!-- Subject -->
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="far fa-comment"></i></span>
                                <input type="text" class="form-control" name="subject"
                                       placeholder="Email Subject" required>
                                <div class="invalid-feedback">Please provide an email subject.</div>
                            </div>

                            <!-- Attachment -->
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="fas fa-paperclip"></i></span>
                                <input type="file" class="form-control" name="attachment[]">
                            </div>

                            <!-- Body -->
                            <div class="mb-3">
                                <label class="form-label">Email Message</label>
                                <textarea class="form-control" name="emailBody" id="emailBody" rows="10"><?= "\n\nRegards\n" . $h($fullname) . "\nCrop Monitor Consultant\n" . $h($email) ?></textarea>
                            </div>

                            <button name="send" id="send" type="submit" class="btn btn-primary">Submit</button>
                        </form>
                    </div>
                </div>
            </div>
        </main>

        <?php include __DIR__ . '/../layouts/footer.php'; ?>
    </div>
</div>

<script>
(function () {
    'use strict';
    window.addEventListener('load', function () {
        var forms = document.getElementsByClassName('needs-validation');
        Array.prototype.forEach.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();
</script>
