<?php
/**
 * Contact Form Handler
 * Processes contact form submissions and saves to database
 * REQUIRES: User must be logged in
 */

session_start();
header('Content-Type: application/json');

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

// CHECK AUTHENTICATION - User must be logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Please login first to send a message',
        'redirect' => 'auth-system/login.php?redirect=../contact.php',
        'error_code' => 'NOT_LOGGED_IN'
    ]);
    exit;
}

// Get database connection
require_once 'config/db.php';

// Sanitize and validate inputs
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['number'] ?? '');
$subject = trim($_POST['subject'] ?? '');
$message = trim($_POST['message'] ?? '');
$agree_privacy = isset($_POST['html']) ? 1 : 0;

// Validation
$errors = [];

if (empty($name)) {
    $errors[] = 'Name is required';
}

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = 'Valid email is required';
}

if (empty($phone)) {
    $errors[] = 'Phone number is required';
}

if (empty($subject)) {
    $errors[] = 'Please select a service';
}

if (empty($message)) {
    $errors[] = 'Message is required';
}

if (!$agree_privacy) {
    $errors[] = 'You must agree to the privacy policy';
}

// Return validation errors
if (!empty($errors)) {
    echo json_encode([
        'success' => false,
        'message' => 'Please fix the following errors: ' . implode(', ', $errors),
        'errors' => $errors
    ]);
    exit;
}

// Insert into database
$stmt = $connection->prepare("
    INSERT INTO contact_messages (name, email, phone, subject, message, privacy_agreed, created_at)
    VALUES (?, ?, ?, ?, ?, ?, NOW())
");

if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $connection->error]);
    exit;
}

$stmt->bind_param('sssss', $name, $email, $phone, $subject, $message);
$privacy_agreed = $agree_privacy;

// Prepare statement with user_id
$user_id = $_SESSION['user_id'];
$stmt = $connection->prepare("
    INSERT INTO contact_messages (user_id, name, email, phone, subject, message, privacy_agreed, created_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
");
$stmt->bind_param('isssssi', $user_id, $name, $email, $phone, $subject, $message, $privacy_agreed);

if ($stmt->execute()) {
    $message_id = $stmt->insert_id;
    
    // Send confirmation email to user
    sendConfirmationEmail($name, $email, $subject);
    
    // Send notification to admin
    sendAdminNotification($name, $email, $phone, $subject, $message);
    
    echo json_encode([
        'success' => true,
        'message' => 'Thank you! Your message has been sent. Our admin team will review it shortly.',
        'message_id' => $message_id,
        'redirect' => 'contact.php'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save your message. Please try again.'
    ]);
}

$stmt->close();
$connection->close();

/**
 * Send confirmation email to user
 */
function sendConfirmationEmail($name, $email, $subject) {
    try {
        require_once 'classes/DirectSMTPService.php';
        $emailService = new DirectSMTPService();
        
        $email_subject = "We Received Your Message - Interior Design Solutions";
        $email_body = "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background: linear-gradient(135deg, #d4a574 0%, #b8956f 100%); color: white; padding: 30px; text-align: center; border-radius: 5px 5px 0 0; }
                .content { padding: 30px; background-color: #f9f9f9; border-left: 4px solid #d4a574; }
                .footer { background-color: #333; color: white; padding: 20px; text-align: center; font-size: 12px; border-radius: 0 0 5px 5px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Thank You for Contacting Us!</h1>
                </div>
                <div class='content'>
                    <p>Hello <strong>$name</strong>,</p>
                    
                    <p>We have successfully received your message regarding <strong>$subject</strong>.</p>
                    
                    <p>Our team will review your inquiry and get back to you shortly. We appreciate your interest in our services!</p>
                    
                    <p>If you have any urgent matters, please feel free to call us directly.</p>
                    
                    <p><strong>Best regards,</strong><br>Interior Design Solutions Team</p>
                </div>
                <div class='footer'>
                    <p>&copy; 2026 Interior Design Solutions. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $result = $emailService->sendEmail($email, $email_subject, $email_body, true);
        
        if ($result['success']) {
            error_log("✓ Confirmation email sent to: $email");
        } else {
            error_log("✗ Failed to send confirmation email to: $email");
        }
    } catch (Exception $e) {
        error_log("Error sending confirmation email: " . $e->getMessage());
    }
}

/**
 * Send notification to admin
 */
function sendAdminNotification($name, $email, $phone, $subject, $message) {
    try {
        require_once 'classes/DirectSMTPService.php';
        $emailService = new DirectSMTPService();
        
        // Send to admin email
        $admin_email = 'admin@interiordesign.com';
        $email_subject = "New Contact Form Submission - $subject";
        $email_body = "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .container { max-width: 600px; margin: 0 auto; }
                .header { background: linear-gradient(135deg, #d4a574 0%, #b8956f 100%); color: white; padding: 20px; text-align: center; border-radius: 5px 5px 0 0; }
                .content { padding: 20px; background-color: #f9f9f9; }
                .field { margin: 15px 0; padding: 10px; background: white; border-left: 3px solid #d4a574; }
                .label { font-weight: bold; color: #d4a574; }
                .footer { background-color: #333; color: white; padding: 15px; text-align: center; font-size: 12px; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>📬 New Contact Form Submission</h1>
                </div>
                <div class='content'>
                    <div class='field'>
                        <div class='label'>Name:</div>
                        <div>$name</div>
                    </div>
                    <div class='field'>
                        <div class='label'>Email:</div>
                        <div><a href='mailto:$email'>$email</a></div>
                    </div>
                    <div class='field'>
                        <div class='label'>Phone:</div>
                        <div><a href='tel:$phone'>$phone</a></div>
                    </div>
                    <div class='field'>
                        <div class='label'>Service:</div>
                        <div>$subject</div>
                    </div>
                    <div class='field'>
                        <div class='label'>Message:</div>
                        <div>" . nl2br(htmlspecialchars($message)) . "</div>
                    </div>
                </div>
                <div class='footer'>
                    <p>Received: " . date('Y-m-d H:i:s') . "</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $result = $emailService->sendEmail($admin_email, $email_subject, $email_body, true);
        
        if ($result['success']) {
            error_log("✓ Admin notification sent for: $email");
        } else {
            error_log("✗ Failed to send admin notification");
        }
    } catch (Exception $e) {
        error_log("Error sending admin notification: " . $e->getMessage());
    }
}
?>
