<?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: ' . $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("Prepare failed: " . $connection->error);
    }
    
    $stmt->bind_param("i", $consultation_id);
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $consultation = $result->fetch_assoc();
    
    if (!$consultation) {
        throw new Exception("Consultation not found with ID: " . $consultation_id);
    }
    
    // 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 declined
    $update_stmt = $connection->prepare("UPDATE consultations SET status = 'declined', updated_at = NOW() WHERE id = ?");
    if (!$update_stmt) {
        throw new Exception("Prepare update failed: " . $connection->error);
    }
    
    $update_stmt->bind_param("i", $consultation_id);
    if (!$update_stmt->execute()) {
        throw new Exception("Update failed: " . $update_stmt->error);
    }
    
    // Send decline email
    $to = $recipient_email;
    $subject = "Consultation Request Status Update - 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']));
    
    $message = "
    <html>
    <head>
        <style>
            body { font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; background: #f9f7f4; }
            .header { background: linear-gradient(135deg, #8b6f47 0%, #6b5738 100%); color: white; padding: 30px; border-radius: 10px 10px 0 0; text-align: center; }
            .content { background: white; padding: 30px; border-radius: 0 0 10px 10px; }
            .decline-badge { background: #fee2e2; color: #991b1b; padding: 15px; border-radius: 8px; margin: 20px 0; border: 1px solid #fecaca; text-align: center; font-weight: bold; font-size: 18px; }
            .details { background: #f9f7f4; padding: 20px; border-radius: 8px; margin: 20px 0; }
            .detail-row { margin: 10px 0; }
            .label { font-weight: 600; color: #8b6f47; }
            .next-steps { background: #fef3c7; padding: 20px; border-radius: 8px; border-left: 4px solid #d4a574; }
            .footer { text-align: center; padding: 20px; color: #999; font-size: 12px; border-top: 1px solid #e0e0e0; margin-top: 20px; }
        </style>
    </head>
    <body>
        <div class=\"container\">
            <div class=\"header\">
                <h1 style=\"margin: 0; font-size: 28px;\">Consultation Request Update</h1>
            </div>
            
            <div class=\"content\">
                <p>Hello <strong>" . htmlspecialchars($name) . "</strong>,</p>
                
                <p>Thank you for submitting your consultation request with Interior Design Solutions.</p>
                
                <div class=\"decline-badge\">
                    Status: Request Not Approved at This Time
                </div>
                
                <h3 style=\"color: #8b6f47; margin-top: 30px;\">Your Consultation Details:</h3>
                <div class=\"details\">
                    <div class=\"detail-row\">
                        <span class=\"label\">Consultation Type:</span> " . htmlspecialchars($consultation_type) . "
                    </div>
                    <div class=\"detail-row\">
                        <span class=\"label\">Preferred Date:</span> " . htmlspecialchars($preferred_date) . "
                    </div>
                </div>
                
                <div class=\"next-steps\">
                    <h3 style=\"margin-top: 0; color: #8b6f47;\">What you can do:</h3>
                    <ul style=\"margin: 10px 0; padding-left: 20px;\">
                        <li>Feel free to reach out to us directly if you have questions</li>
                        <li>You can submit a new consultation request in the future</li>
                        <li>Contact us to discuss alternative options</li>
                        <li>Visit our website to explore our services and portfolio</li>
                    </ul>
                </div>
                
                <p>We appreciate your interest in our services and hope to work with you in the future. If you have any questions, please don't hesitate to contact us.</p>
                
                <p>
                    Best regards,<br>
                    <strong>Interior Design Solutions Team</strong><br>
                    <em>Creating spaces you'll love</em>
                </p>
                
                <div class=\"footer\">
                    <p>This is an automated email. Please do not reply directly to this message.</p>
                    <p>&copy; 2025 Interior Design Solutions. All rights reserved.</p>
                </div>
            </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("✓ Decline email SENT to: $to for consultation ID: $consultation_id");
    } else {
        if ($send_email) {
            error_log("✗ Decline email FAILED for: $to - Storing in queue");
            
            // Queue email if sending fails
            $queue_stmt = $connection->prepare("
                INSERT INTO email_queue (consultation_id, recipient_email, subject, body, email_type, status)
                VALUES (?, ?, ?, ?, 'decline', 'pending')
            ");
            
            if ($queue_stmt) {
                $queue_stmt->bind_param("isss", $consultation_id, $to, $subject, $message);
                $queue_stmt->execute();
            }
        } else {
            error_log("Email sending disabled - Consultation ID: $consultation_id declined without email");
        }
    }
    
    if ($email_sent) {
        error_log("Decline email sent to: $to for consultation ID: $consultation_id");
        
        // Add admin notification
        $admin_id = $_SESSION['user_id'];
        $notification_msg = "Consultation declined for " . htmlspecialchars($name);
        
        $notif_stmt = $connection->prepare("
            INSERT INTO notifications (admin_id, consultation_id, type, message, status, created_at)
            VALUES (?, ?, 'decline', ?, '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 declined and notification sent to ' . htmlspecialchars($to),
            'notification_type' => 'decline',
            'recipient' => htmlspecialchars($name),
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    } else {
        // Queue email if sending fails
        error_log("Failed to send decline email to: $to - Storing in queue");
        
        $queue_stmt = $connection->prepare("
            INSERT INTO email_queue (consultation_id, recipient_email, subject, body, email_type, status)
            VALUES (?, ?, ?, ?, 'decline', 'pending')
        ");
        
        if ($queue_stmt) {
            $queue_stmt->bind_param("isss", $consultation_id, $to, $subject, $message);
            $queue_stmt->execute();
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Consultation declined. Email queued for delivery.',
            'notification_type' => 'decline',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
    
} catch (Exception $e) {
    error_log("Decline consultation error for ID " . $consultation_id . ": " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
} finally {
    if (isset($connection)) {
        $connection->close();
    }
}
?>
