<?php
/**
 * Submit Consultation Form
 * Handles consultation requests from customer dashboard
 */

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

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

// Database connection
$host = 'localhost';
$db = 'zemaraim_interior';
$user = 'zemaraim';
$password = '8wwxk]-X3Kx]CJ]5';

$conn = new mysqli($host, $user, $password, $db);

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

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Validate required fields
$required_fields = ['first_name', 'last_name', 'email', 'phone', 'address', 'consultation_type', 'preferred_date', 'preferred_time', 'project_description', 'budget_range'];

foreach ($required_fields as $field) {
    if (!isset($input[$field]) || trim($input[$field]) === '') {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Missing required field: ' . $field
        ]);
        exit;
    }
}

// Sanitize and validate inputs
$first_name = trim($input['first_name']);
$last_name = trim($input['last_name']);
$email = trim($input['email']);
$phone = trim($input['phone']);
$address = trim($input['address']);
$consultation_type = trim($input['consultation_type']);
$preferred_date = trim($input['preferred_date']);
$preferred_time = trim($input['preferred_time']);
$project_description = trim($input['project_description']);
$budget_range = trim($input['budget_range']);
$source = isset($input['source']) ? trim($input['source']) : '';
$user_id = $_SESSION['user_id'];

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid email address'
    ]);
    exit;
}

// Validate phone format (basic validation)
if (strlen($phone) < 10) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid phone number'
    ]);
    exit;
}

// Validate date is in future
$today = new DateTime();
$selected_date = DateTime::createFromFormat('Y-m-d', $preferred_date);

if ($selected_date === false || $selected_date < $today) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Please select a future date'
    ]);
    exit;
}

try {
    // Check if consultations table exists
    $table_check = $conn->query("SHOW TABLES LIKE 'consultations'");
    
    if ($table_check && $table_check->num_rows === 0) {
        // Create consultations table if it doesn't exist
        $create_table_sql = "
            CREATE TABLE `consultations` (
                `id` INT AUTO_INCREMENT PRIMARY KEY,
                `user_id` INT NOT NULL,
                `first_name` VARCHAR(100) NOT NULL,
                `last_name` VARCHAR(100) NOT NULL,
                `email` VARCHAR(100) NOT NULL,
                `phone` VARCHAR(20) NOT NULL,
                `address` TEXT NOT NULL,
                `consultation_type` VARCHAR(100) NOT NULL,
                `preferred_date` DATE NOT NULL,
                `preferred_time` TIME NOT NULL,
                `project_description` TEXT NOT NULL,
                `budget_range` VARCHAR(100) NOT NULL,
                `source` VARCHAR(100),
                `status` ENUM('pending', 'confirmed', 'completed', 'cancelled') DEFAULT 'pending',
                `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            )
        ";
        
        if (!$conn->query($create_table_sql)) {
            throw new Exception("Failed to create consultations table: " . $conn->error);
        }
    }

    // Insert consultation into database
    $stmt = $conn->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: " . $conn->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("Execute failed: " . $stmt->error);
    }

    $consultation_id = $conn->insert_id;
    $stmt->close();

    // Log the consultation request
    error_log("New consultation submitted - ID: $consultation_id, User: $user_id, Email: $email, Type: $consultation_type");

    // Send response
    echo json_encode([
        'success' => true,
        'message' => 'Consultation request submitted successfully',
        'consultation_id' => $consultation_id
    ]);

} catch (Exception $e) {
    http_response_code(500);
    error_log("Error submitting consultation: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error submitting consultation: ' . $e->getMessage()
    ]);
}

$conn->close();
?>
