<?php
error_reporting(0);
ini_set('display_errors', 0);

session_start();

header('Content-Type: application/json; charset=utf-8');

// Login is NOT required — guests can submit consultations
$isLoggedIn = isset($_SESSION['user_id']);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request method'
    ]);
    exit;
}

// Database connection
require_once '../config/db.php';
require_once '../classes/DirectSMTPService.php';

if (!isset($connection) || $connection->connect_error) {
    echo json_encode([
        'success' => false,
        'message' => 'Database connection failed'
    ]);
    exit;
}

function ensureEmailQueueTable($connection) {
    $create_table_sql = "
    CREATE TABLE IF NOT EXISTS email_queue (
        id INT PRIMARY KEY AUTO_INCREMENT,
        consultation_id INT,
        recipient_email VARCHAR(255) NOT NULL,
        subject VARCHAR(255) NOT NULL,
        body LONGTEXT NOT NULL,
        email_type VARCHAR(50),
        status VARCHAR(20) DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        sent_at TIMESTAMP NULL,
        attempts INT DEFAULT 0,
        last_attempt TIMESTAMP NULL,
        error_message TEXT
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ";
    $connection->query($create_table_sql);
}

function queueEmail($connection, $consultation_id, $to, $subject, $message, $error_message = null) {
    ensureEmailQueueTable($connection);
    $queue_stmt = $connection->prepare("
        INSERT INTO email_queue (
            consultation_id, recipient_email, subject, body, email_type, status, error_message
        ) VALUES (?, ?, ?, ?, 'consultation_confirmation', 'pending', ?)
    ");

    if ($queue_stmt) {
        $queue_stmt->bind_param("issss", $consultation_id, $to, $subject, $message, $error_message);
        $queue_stmt->execute();
        $queue_stmt->close();
        return true;
    }
    return false;
}

// Get user_id if logged in, NULL for guests
$user_id = $isLoggedIn ? $_SESSION['user_id'] : null;

// Get form data from POST (works for both guests and logged-in users)
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$address = trim($_POST['address'] ?? '');
$consultation_type = trim($_POST['consultation_type'] ?? '');
$preferred_date = trim($_POST['preferred_date'] ?? '');
$preferred_time = trim($_POST['preferred_time'] ?? '');
$project_description = trim($_POST['project_description'] ?? '');
$budget_range = trim($_POST['budget_range'] ?? '');
$source = trim($_POST['source'] ?? '');

// Validation
$errors = [];
if (empty($first_name)) $errors[] = 'First name is required';
if (empty($last_name)) $errors[] = 'Last name is required';
if (empty($consultation_type)) $errors[] = 'Consultation type is required';
if (empty($preferred_date)) $errors[] = 'Preferred date is required';
if (empty($budget_range)) $errors[] = 'Budget range is required';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'A valid email is required';

if (!empty($errors)) {
    echo json_encode([
        'success' => false,
        'message' => implode(', ', $errors)
    ]);
    exit;
}

try {
    // Insert consultation into database — handle NULL user_id for guests
    if ($user_id !== null) {
        $stmt = $connection->prepare("
            INSERT INTO consultations (
                user_id, first_name, last_name, email, phone, address,
                consultation_type, preferred_date, preferred_time,
                project_description, budget_range, source, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
        ");
        if (!$stmt) throw new Exception("Prepare failed: " . $connection->error);
        $stmt->bind_param(
            "isssssssssss",
            $user_id, $first_name, $last_name, $email, $phone, $address,
            $consultation_type, $preferred_date, $preferred_time,
            $project_description, $budget_range, $source
        );
    } else {
        $stmt = $connection->prepare("
            INSERT INTO consultations (
                user_id, first_name, last_name, email, phone, address,
                consultation_type, preferred_date, preferred_time,
                project_description, budget_range, source, status
            ) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
        ");
        if (!$stmt) throw new Exception("Prepare failed: " . $connection->error);
        $stmt->bind_param(
            "sssssssssss",
            $first_name, $last_name, $email, $phone, $address,
            $consultation_type, $preferred_date, $preferred_time,
            $project_description, $budget_range, $source
        );
    }
    
    if (!$stmt->execute()) {
        throw new Exception("Error submitting consultation: " . $stmt->error);
    }
    
    $consultation_id = $connection->insert_id;
    
    // Send confirmation email to user
    $to = $email;
    $subject = "Consultation Request Received - Faren Interior Design";
    
    $consultation_type_display = ucfirst(str_replace('_', ' ', $consultation_type));
    $preferred_date_formatted = date('F d, Y', strtotime($preferred_date));
    
    $message = '<html><head><style>';
    $message .= 'body { font-family: Segoe UI, Arial, sans-serif; line-height: 1.6; color: #333; }';
    $message .= '.container { max-width: 600px; margin: 0 auto; padding: 20px; background: #f9f7f4; }';
    $message .= '.header { background: linear-gradient(135deg, #8b6f47 0%, #6b5738 100%); color: white; padding: 30px; border-radius: 10px 10px 0 0; text-align: center; }';
    $message .= '.content { background: white; padding: 30px; border-radius: 0 0 10px 10px; }';
    $message .= '.confirmation-badge { background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin: 20px 0; border: 1px solid #c3e6cb; text-align: center; font-weight: bold; }';
    $message .= '.details { background: #f9f7f4; padding: 20px; border-radius: 8px; margin: 20px 0; }';
    $message .= '.detail-row { margin: 10px 0; }';
    $message .= '.label { font-weight: 600; color: #8b6f47; }';
    $message .= '.next-steps { background: #e7f3ff; padding: 20px; border-radius: 8px; border-left: 4px solid #d4a574; }';
    $message .= '</style></head><body>';
    $message .= '<div class="container">';
    $message .= '<div class="header"><h1 style="margin: 0; font-size: 28px;">Thank You!</h1></div>';
    $message .= '<div class="content">';
    $message .= '<p>Hello <strong>' . htmlspecialchars($first_name) . '</strong>,</p>';
    $message .= '<p>We have received your consultation request and appreciate your interest in Faren Interior Design.</p>';
    $message .= '<div class="confirmation-badge">Your request has been received</div>';
    $message .= '<h3 style="color: #8b6f47;">Your Consultation Details:</h3>';
    $message .= '<div class="details">';
    $message .= '<div class="detail-row"><span class="label">Consultation Type:</span> ' . htmlspecialchars($consultation_type_display) . '</div>';
    $message .= '<div class="detail-row"><span class="label">Preferred Date:</span> ' . htmlspecialchars($preferred_date_formatted) . '</div>';
    $message .= '<div class="detail-row"><span class="label">Preferred Time:</span> ' . htmlspecialchars($preferred_time) . '</div>';
    $message .= '<div class="detail-row"><span class="label">Budget Range:</span> ' . htmlspecialchars($budget_range) . '</div>';
    $message .= '</div>';
    $message .= '<div class="next-steps">';
    $message .= '<h3 style="margin-top: 0; color: #0066cc;">What happens next?</h3>';
    $message .= '<ul><li>Our team will review your consultation request</li>';
    $message .= '<li>We will contact you within 24 hours to confirm the appointment</li>';
    $message .= '<li>We will discuss your project requirements in detail</li>';
    $message .= '<li>You will receive a customized proposal</li></ul>';
    $message .= '</div>';
    $message .= '<p>If you have any questions before we contact you, please reply to this email.</p>';
    $message .= '<p>Best regards,<br>Faren Interior Design Team</p>';
    $message .= '</div></div></body></html>';
    
    // Send email via SMTP service (with queue fallback)
    $email_sent = false;
    $email_error = null;
    $mailService = new DirectSMTPService();
    $mailResult = $mailService->sendEmail($to, $subject, $message, true);

    if (is_array($mailResult) && !empty($mailResult['success'])) {
        $email_sent = true;
        error_log("Consultation confirmation email sent to: $to");
    } else {
        $email_error = is_array($mailResult) ? ($mailResult['message'] ?? 'Unknown mail error') : 'Unknown mail error';
        queueEmail($connection, $consultation_id, $to, $subject, $message, $email_error);
        error_log("Consultation email queued for: $to. Reason: " . $email_error);
    }
    
    echo json_encode([
        'success' => true,
        'message' => $email_sent
            ? 'Consultation request submitted successfully! Confirmation email sent.'
            : 'Consultation request submitted successfully! Email is queued and will be sent shortly.',
        'consultation_id' => $consultation_id,
        'email_sent' => $email_sent
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} finally {
    $connection->close();
}
?>
