<?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 and is admin
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Not logged in'
    ]);
    exit;
}

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode([
        'success' => false,
        'message' => 'Not authorized - admin access required'
    ]);
    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)) {
    echo json_encode([
        'success' => false,
        'message' => 'Database connection failed'
    ]);
    exit;
}

$consultation_id = isset($_POST['consultation_id']) ? intval($_POST['consultation_id']) : 0;

if ($consultation_id <= 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid consultation ID'
    ]);
    exit;
}

// Check if email sending is enabled
$send_email = isset($_POST['send_email']) ? $_POST['send_email'] === '1' : true;

try {
    // Get consultation details AND user's registered email
    $stmt = $connection->prepare("
        SELECT c.id, c.first_name, c.last_name, c.email as consultation_email, c.consultation_type, 
               c.preferred_date, c.budget_range, c.user_id,
               u.email as user_email
        FROM consultations c
        LEFT JOIN users u ON c.user_id = u.id
        WHERE c.id = ?
    ");
    if (!$stmt) {
        throw new Exception("Query prepare failed: " . $connection->error);
    }
    
    $stmt->bind_param("i", $consultation_id);
    if (!$stmt->execute()) {
        throw new Exception("Query execute failed: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $consultation = $result->fetch_assoc();
    
    if (!$consultation) {
        throw new Exception("Consultation not found");
    }
    
    // Use registered user email if available, otherwise use consultation email
    $recipient_email = !empty($consultation['user_email']) ? $consultation['user_email'] : $consultation['consultation_email'];
    
    // Update consultation status to approved
    $update_stmt = $connection->prepare("UPDATE consultations SET status = ?, updated_at = NOW() WHERE id = ?");
    if (!$update_stmt) {
        throw new Exception("Update prepare failed: " . $connection->error);
    }
    
    $status = 'approved';
    $update_stmt->bind_param("si", $status, $consultation_id);
    if (!$update_stmt->execute()) {
        throw new Exception("Update execute failed: " . $update_stmt->error);
    }
    
    // Send approval email
    $to = $recipient_email;
    $subject = "Your Consultation Request Has Been Approved - Interior Design Solutions";
    
    $name = trim($consultation['first_name'] . ' ' . $consultation['last_name']);
    $consultation_type = ucfirst(str_replace('_', ' ', $consultation['consultation_type']));
    $preferred_date = date('F d, Y', strtotime($consultation['preferred_date']));
    $budget_range = $consultation['budget_range'];
    
    $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 .= '.approval-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 .= '.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;">Consultation Approved!</h1></div>';
    $message .= '<div class="content">';
    $message .= '<p>Hello <strong>' . htmlspecialchars($name) . '</strong>,</p>';
    $message .= '<p>Great news! Your consultation request has been approved by our Interior Design Solutions team.</p>';
    $message .= '<div class="approval-badge">Your consultation has been approved</div>';
    $message .= '<h3 style="color: #8b6f47;">Your Consultation Details:</h3>';
    $message .= '<div class="details">';
    $message .= '<div>Consultation Type: ' . htmlspecialchars($consultation_type) . '</div>';
    $message .= '<div>Preferred Date: ' . htmlspecialchars($preferred_date) . '</div>';
    $message .= '<div>Budget Range: ' . 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 contact you within 24 hours</li>';
    $message .= '<li>We will discuss your project requirements</li>';
    $message .= '<li>You will receive a customized proposal</li></ul>';
    $message .= '</div>';
    $message .= '<p>If you have any questions, please contact us.</p>';
    $message .= '<p>Best regards,<br>Interior Design Solutions Team</p>';
    $message .= '</div></div></body></html>';
    
    // Set email headers for HTML
    $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";
    
    // Send email
    $email_sent = false;
    if ($send_email && @mail($to, $subject, $message, $headers)) {
        $email_sent = true;
        error_log("✓ Approval email SENT to: $to for consultation ID: $consultation_id");
    } else {
        if ($send_email) {
            error_log("✗ Approval email FAILED for: $to - Storing in queue for consultation ID: $consultation_id");
            
            // Queue email if sending fails
            $queue_stmt = $connection->prepare("
                INSERT INTO email_queue (consultation_id, recipient_email, subject, body, email_type, status)
                VALUES (?, ?, ?, ?, 'approval', 'pending')
            ");
            
            if ($queue_stmt) {
                $queue_stmt->bind_param("isss", $consultation_id, $to, $subject, $message);
                if ($queue_stmt->execute()) {
                    error_log("✓ Email queued successfully for: $to (Queue ID: " . $connection->insert_id . ")");
                } else {
                    error_log("✗ Failed to queue email for: $to - Error: " . $queue_stmt->error);
                }
            } else {
                error_log("✗ Failed to prepare queue statement for: $to - Error: " . $connection->error);
            }
        } else {
            error_log("Email sending disabled - Consultation ID: $consultation_id approved without email");
        }
    }
    
    // Add admin notification
    $admin_id = $_SESSION['user_id'];
    $notification_msg = "Consultation approved for " . htmlspecialchars($name);
    
    $notif_stmt = $connection->prepare("
        INSERT INTO notifications (admin_id, consultation_id, type, message, status, created_at)
        VALUES (?, ?, 'approval', ?, 'unread', NOW())
    ");
    
    if ($notif_stmt) {
        $notif_stmt->bind_param("iis", $admin_id, $consultation_id, $notification_msg);
        $notif_stmt->execute();
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Consultation approved successfully! Approval email sent to ' . htmlspecialchars($to),
        'notification_type' => 'approval',
        'recipient' => htmlspecialchars($name),
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
} finally {
    if (isset($connection)) {
        $connection->close();
    }
}
?>
