<?php
session_start();
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/email.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$response = ['success' => false, 'message' => 'An error occurred'];

// Get POST data
$first_name = isset($_POST['first_name']) ? trim($_POST['first_name']) : '';
$last_name = isset($_POST['last_name']) ? trim($_POST['last_name']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$address = isset($_POST['address']) ? trim($_POST['address']) : '';
$consultation_type = isset($_POST['consultation_type']) ? trim($_POST['consultation_type']) : '';
$preferred_date = isset($_POST['preferred_date']) ? trim($_POST['preferred_date']) : '';
$preferred_time = isset($_POST['preferred_time']) ? trim($_POST['preferred_time']) : '';
$project_description = isset($_POST['project_description']) ? trim($_POST['project_description']) : '';
$budget_range = isset($_POST['budget_range']) ? trim($_POST['budget_range']) : '';
$source = isset($_POST['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($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required';
if (empty($phone)) $errors[] = 'Phone number is required';
if (empty($address)) $errors[] = 'Address is required';
if (empty($consultation_type)) $errors[] = 'Consultation type is required';
if (empty($preferred_date)) $errors[] = 'Preferred date is required';
if (empty($preferred_time)) $errors[] = 'Preferred time is required';
if (empty($project_description)) $errors[] = 'Project description is required';
if (empty($budget_range)) $errors[] = 'Budget range is required';

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

// Create verification token
$verification_token = bin2hex(random_bytes(32));
$token_expiry = date('Y-m-d H:i:s', strtotime('+24 hours'));

// Save consultation request
$query = "INSERT INTO consultations (user_id, first_name, last_name, email, phone, address, consultation_type, preferred_date, preferred_time, project_description, budget_range, source, verification_token, token_expiry, status, created_at) 
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";

$stmt = $conn->prepare($query);
if (!$stmt) {
    $response['message'] = 'Database error: ' . $conn->error;
    echo json_encode($response);
    exit;
}

$status = 'pending';
$stmt->bind_param("isssssssssss", $user_id, $first_name, $last_name, $email, $phone, $address, $consultation_type, $preferred_date, $preferred_time, $project_description, $budget_range, $source);

// Add token and expiry separately
$query = "INSERT INTO consultations (user_id, first_name, last_name, email, phone, address, consultation_type, preferred_date, preferred_time, project_description, budget_range, source, verification_token, token_expiry, status, created_at) 
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";

$stmt = $conn->prepare($query);
$stmt->bind_param("isssssssssss", $user_id, $first_name, $last_name, $email, $phone, $address, $consultation_type, $preferred_date, $preferred_time, $project_description, $budget_range, $source, $verification_token, $token_expiry);

if (!$stmt->execute()) {
    $response['message'] = 'Failed to save consultation request';
    echo json_encode($response);
    exit;
}

$consultation_id = $stmt->insert_id;

// Send verification email
$verification_link = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . "/verify-consultation.php?token=" . $verification_token . "&id=" . $consultation_id;

$subject = "Verify Your Consultation Request - Interior Design";
$message = "
<h2>Verify Your Consultation Request</h2>
<p>Hello $first_name,</p>
<p>Thank you for requesting a consultation with us. Please verify your email address by clicking the link below:</p>
<p><a href='$verification_link' style='background: #d4a33a; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;'>Verify Email Address</a></p>
<p>Or copy this link: <br>$verification_link</p>
<p>This link expires in 24 hours.</p>
<p>Best regards,<br>Interior Design Team</p>
";

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
$headers .= "From: noreply@interiordesign.com" . "\r\n";

$mail_sent = mail($email, $subject, $message, $headers);

if (!$mail_sent) {
    // Consultation saved but email failed - still return success to user
    $response['success'] = true;
    $response['message'] = 'Consultation request submitted! Please check your email for verification.';
    echo json_encode($response);
    exit;
}

$response['success'] = true;
$response['message'] = 'Consultation request submitted! Please verify your email address.';
echo json_encode($response);
?>
