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

session_start();

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Please log in to submit a consultation request'
    ]);
    exit;
}

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

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

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

// Get user info
$user_id = $_SESSION['user_id'];
$stmt = $connection->prepare("SELECT name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

// Get form data from POST
$consultation_type = trim($_POST['consultation_type'] ?? '');
$preferred_date = trim($_POST['preferred_date'] ?? '');
$budget_range = trim($_POST['budget_range'] ?? '');
$project_description = trim($_POST['project_description'] ?? '');
$email = $user['email'] ?? '';
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$preferred_time = trim($_POST['preferred_time'] ?? '');
$address = trim($_POST['address'] ?? '');
$source = trim($_POST['source'] ?? '');

// Validation
$errors = [];
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($errors)) {
    echo json_encode([
        'success' => false,
        'message' => implode(', ', $errors)
    ]);
    exit;
}

try {
    // Insert consultation into database
    $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
    );
    
    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 - Interior Design Solutions";
    
    $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 Interior Design Solutions.</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>Interior Design Solutions Team</p>';
    $message .= '</div></div></body></html>';
    
    // Try sending email
    $email_sent = false;
    
    // Method 1: Try standard PHP mail()
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";
    $headers .= "From: noreply@interiordesign.com\r\n";
    $headers .= "Reply-To: admin@interiordesign.com\r\n";
    
    if (@mail($to, $subject, $message, $headers)) {
        $email_sent = true;
        error_log("Email sent via mail() to: $to");
    } else {
        error_log("Mail failed for: $to - Storing in email queue");
        
        // Save to email queue for later sending
        $queue_stmt = $connection->prepare("
            INSERT INTO email_queue (consultation_id, recipient_email, subject, body, email_type, status)
            VALUES (?, ?, ?, ?, 'consultation_confirmation', 'pending')
        ");
        
        if ($queue_stmt) {
            $queue_stmt->bind_param("isss", $consultation_id, $to, $subject, $message);
            $queue_stmt->execute();
            error_log("Email queued for: $to");
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Consultation request submitted successfully! Please check your email for confirmation.',
        'consultation_id' => $consultation_id
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} finally {
    $connection->close();
}
?>
