<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require_once 'config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

// Sanitize helper
function sanitize_input($data) {
    if ($data === null || $data === '') {
        return '';
    }
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

// Helper function to format service names
function format_service_name($service_key) {
    $services = [
        'studio-photography' => 'Studio Photography',
        'wedding-photography' => 'Wedding Photography',
        'event-coverage' => 'Event Coverage',
        'outdoor-photography' => 'Outdoor Photography',
        'video-production' => 'Video Production',
        'music-video' => 'Music Video Production',
        'podcast-production' => 'Podcast Production',
        'commercial' => 'Commercial / Corporate',
        'drone' => 'Drone / Aerial Services',
        'other' => 'Other'
    ];
    
    return $services[$service_key] ?? $service_key;
}

// Helper function to format budget ranges
function format_budget($budget_key) {
    $budgets = [
        'below-500k' => 'Below UGX 500,000',
        '500k-1m' => 'UGX 500,000 - 1,000,000',
        '1m-2m' => 'UGX 1,000,000 - 2,000,000',
        '2m-5m' => 'UGX 2,000,000 - 5,000,000',
        'above-5m' => 'Above UGX 5,000,000'
    ];
    
    return $budgets[$budget_key] ?? $budget_key;
}

// Get and sanitize input fields (updated to match new form)
$name        = sanitize_input($_POST['name'] ?? '');
$email       = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
$phone       = sanitize_input($_POST['phone'] ?? '');
$address     = sanitize_input($_POST['address'] ?? '');
$service     = sanitize_input($_POST['service'] ?? '');
$budget      = sanitize_input($_POST['budget'] ?? '');
$event_date  = sanitize_input($_POST['event-date'] ?? '');
$message     = sanitize_input($_POST['message'] ?? '');
$privacy     = isset($_POST['privacy']) ? true : false;

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Please provide a valid email address.']);
    exit;
}

// Validate required fields
$required_fields = ['name', 'email', 'phone', 'service', 'message'];
$missing_fields = [];

foreach ($required_fields as $field) {
    if (empty($$field)) {
        $missing_fields[] = str_replace('_', ' ', $field);
    }
}

// Check privacy policy consent
if (!$privacy) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Please agree to the privacy policy.']);
    exit;
}

if (!empty($missing_fields)) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error', 
        'message' => 'Please fill in all required fields: ' . implode(', ', $missing_fields) . '.'
    ]);
    exit;
}

// Format service name for better readability
$formatted_service = format_service_name($service);
$formatted_budget = $budget ? format_budget($budget) : 'Not specified';

// Get current date and time for tracking
$submission_time = date('Y-m-d H:i:s');
$user_ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$referer = $_SERVER['HTTP_REFERER'] ?? 'Direct visit';

// Build HTML email message for better formatting
$html_message = <<<EOD
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: #4B2E83; color: #fff; padding: 20px; text-align: center; border-radius: 5px 5px 0 0; }
        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 5px 5px; }
        .field { margin-bottom: 20px; border-bottom: 1px solid #eee; padding-bottom: 15px; }
        .field-label { font-weight: bold; color: #4B2E83; display: block; margin-bottom: 5px; }
        .field-value { color: #666; }
        .message-box { background: #fff; padding: 15px; border-left: 4px solid #4B2E83; margin: 20px 0; }
        .footer { font-size: 12px; color: #999; margin-top: 30px; text-align: center; }
        .badge { background: #4B2E83; color: #fff; padding: 3px 8px; border-radius: 3px; font-size: 12px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>New Contact Form Submission</h2>
            <p style="margin:0; opacity:0.9;">Ruffix Culture - Lira City</p>
        </div>
        <div class="content">
            <div class="field">
                <span class="field-label">📋 Submission Details:</span>
                <span class="field-value">Received on {$submission_time}</span>
            </div>
            
            <div class="field">
                <span class="field-label">👤 Name:</span>
                <span class="field-value">{$name}</span>
            </div>
            
            <div class="field">
                <span class="field-label">📧 Email:</span>
                <span class="field-value"><a href="mailto:{$email}">{$email}</a></span>
            </div>
            
            <div class="field">
                <span class="field-label">📞 Phone:</span>
                <span class="field-value"><a href="tel:{$phone}">{$phone}</a></span>
            </div>
            
            <div class="field">
                <span class="field-label">📍 Address/Location:</span>
                <span class="field-value">{$address}</span>
            </div>
            
            <div class="field">
                <span class="field-label">🎯 Service Interested:</span>
                <span class="field-value"><span class="badge">{$formatted_service}</span></span>
            </div>
            
            <div class="field">
                <span class="field-label">💰 Budget Range:</span>
                <span class="field-value">{$formatted_budget}</span>
            </div>
            
            <div class="field">
                <span class="field-label">📅 Preferred Date:</span>
                <span class="field-value">{$event_date}</span>
            </div>
            
            <div class="field">
                <span class="field-label">💬 Message:</span>
                <div class="message-box">
                    <span class="field-value">{$message}</span>
                </div>
            </div>
            
            <div class="field">
                <span class="field-label">📱 Additional Information:</span>
                <span class="field-value">IP Address: {$user_ip}<br>Browser: {$user_agent}<br>Referrer: {$referer}</span>
            </div>
        </div>
        <div class="footer">
            <p>This message was sent from the Ruffix Culture website contact form.</p>
            <p>© " . date('Y') . " Ruffix Culture - Photography & Videography in Lira City</p>
        </div>
    </div>
</body>
</html>
EOD;

// Plain text version for email clients that don't support HTML
$plain_message = <<<EOD
New Contact Form Submission - Ruffix Culture (Lira City)
===================================

SUBMISSION DETAILS:
------------------
Received: {$submission_time}

CONTACT INFORMATION:
------------------
Name: {$name}
Email: {$email}
Phone: {$phone}
Address: {$address}

SERVICE DETAILS:
---------------
Service Interested: {$formatted_service}
Budget Range: {$formatted_budget}
Preferred Date: {$event_date}

MESSAGE:
--------
{$message}

ADDITIONAL INFORMATION:
---------------------
IP Address: {$user_ip}
Browser: {$user_agent}
Referrer: {$referer}

---
This message was sent from the Ruffix Culture website contact form.
© " . date('Y') . " Ruffix Culture - Photography & Videography in Lira City
EOD;

// Send using PHPMailer
$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host       = SMTP_HOST;
    $mail->SMTPAuth   = true;
    $mail->Username   = SMTP_USERNAME;
    $mail->Password   = SMTP_PASSWORD;
    $mail->SMTPSecure = SMTP_SECURE;
    $mail->Port       = SMTP_PORT;

    if (DEBUG_MODE) {
        $mail->SMTPDebug = 2;
        $mail->Debugoutput = 'error_log';
    }

    // Set charset
    $mail->CharSet = 'UTF-8';
    
    // Sender and recipient
    $mail->setFrom(SMTP_USERNAME, EMAIL_HEADER_FROM_NAME);
    $mail->addAddress(SITE_ADMIN_EMAIL);
    $mail->addReplyTo($email, $name);
    
    // Add BCC to team members if needed
    // $mail->addBCC('team@ruffixculture.com', 'Team');
    
    // Email subject with service type for quick identification
    $mail->Subject = EMAIL_SUBJECT_PREFIX . ' ' . SITE_NAME . ' - ' . $formatted_service . ' Inquiry';
    
    // Set both HTML and plain text versions
    $mail->isHTML(true);
    $mail->Body    = $html_message;
    $mail->AltBody = $plain_message;

    // Send email
    $mail->send();
    
    // Send auto-reply to the client
    try {
        $auto_reply = new PHPMailer(true);
        $auto_reply->isSMTP();
        $auto_reply->Host       = SMTP_HOST;
        $auto_reply->SMTPAuth   = true;
        $auto_reply->Username   = SMTP_USERNAME;
        $auto_reply->Password   = SMTP_PASSWORD;
        $auto_reply->SMTPSecure = SMTP_SECURE;
        $auto_reply->Port       = SMTP_PORT;
        $auto_reply->CharSet    = 'UTF-8';
        
        $auto_reply->setFrom(SMTP_USERNAME, 'Ruffix Culture');
        $auto_reply->addAddress($email, $name);
        $auto_reply->Subject = 'Thank You for Contacting Ruffix Culture - Lira City';
        
        $auto_reply_html = <<<EOD
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: #4B2E83; color: #fff; padding: 20px; text-align: center; }
        .content { padding: 30px; background: #f9f9f9; }
        .button { display: inline-block; background: #4B2E83; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>Thank You for Contacting Ruffix Culture!</h2>
        </div>
        <div class="content">
            <p>Dear {$name},</p>
            <p>Thank you for reaching out to Ruffix Culture, your premier photography and videography studio in Lira City.</p>
            <p>We have received your inquiry regarding <strong>{$formatted_service}</strong> and our team will get back to you within 24 hours during business hours (Monday-Friday, 9am-6pm).</p>
            
            <p><strong>Your inquiry details:</strong><br>
            Service: {$formatted_service}<br>
            Preferred Date: {$event_date}<br>
            Budget Range: {$formatted_budget}</p>
            
            <p>In the meantime, feel free to:</p>
            <ul>
                <li>View our portfolio: <a href="https://ruffixculture.com/portfolio">www.ruffixculture.com/portfolio</a></li>
                <li>Check our packages: <a href="https://ruffixculture.com/pricing">www.ruffixculture.com/pricing</a></li>
                <li>Follow us on Instagram: @ruffixculture</li>
            </ul>
            
            <p>For urgent inquiries, please call us at:<br>
            <strong>+256 777 775 388</strong> or <strong>+256 784 006 003</strong></p>
            
            <p>We look forward to capturing your special moments!</p>
            
            <p>Best regards,<br>
            <strong>The Ruffix Culture Team</strong><br>
            Plot 19/21 Bygon Building, Maruzi Road<br>
            Lira City, Uganda</p>
        </div>
    </div>
</body>
</html>
EOD;
        
        $auto_reply->isHTML(true);
        $auto_reply->Body = $auto_reply_html;
        $auto_reply->AltBody = strip_tags($auto_reply_html);
        $auto_reply->send();
    } catch (Exception $e) {
        // Log auto-reply failure but don't affect main response
        error_log("Auto-reply failed: " . $e->getMessage());
    }
    
    // Return success response
    echo json_encode([
        'status' => 'success', 
        'message' => 'Thank you! Your message has been sent successfully. We\'ll get back to you within 24 hours.'
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    error_log("PHPMailer Error: " . $e->getMessage());
    
    $error_message = DEBUG_MODE ? "Mailer Error: {$mail->ErrorInfo}" : 'Unable to send your message at this time. Please try again later or call us directly.';
    
    echo json_encode([
        'status' => 'error',
        'message' => $error_message
    ]);
}
?>