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

session_start();

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Not logged in'
    ]);
    exit;
}

if (!isset($_SESSION['user_role']) || !in_array($_SESSION['user_role'], ['admin', 'staff'], true)) {
    echo json_encode([
        'success' => false,
        'message' => 'Not authorized - admin/staff access required'
    ]);
    exit;
}

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

require_once '../config/db.php';
require_once '../classes/DirectSMTPService.php';

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

function ensureEmailQueueTable($connection) {
    $create_table_sql = "
    CREATE TABLE IF NOT EXISTS email_queue (
        id INT PRIMARY KEY AUTO_INCREMENT,
        consultation_id INT,
        recipient_email VARCHAR(255) NOT NULL,
        subject VARCHAR(255) NOT NULL,
        body LONGTEXT NOT NULL,
        email_type VARCHAR(50),
        status VARCHAR(20) DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        sent_at TIMESTAMP NULL,
        attempts INT DEFAULT 0,
        last_attempt TIMESTAMP NULL,
        error_message TEXT
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ";
    $connection->query($create_table_sql);
}

function queueEmail($connection, $consultation_id, $to, $subject, $message, $email_type, $error_message = null) {
    ensureEmailQueueTable($connection);
    $queue_stmt = $connection->prepare("
        INSERT INTO email_queue (
            consultation_id, recipient_email, subject, body, email_type, status, error_message
        ) VALUES (?, ?, ?, ?, ?, 'pending', ?)
    ");
    if ($queue_stmt) {
        $queue_stmt->bind_param("isssss", $consultation_id, $to, $subject, $message, $email_type, $error_message);
        $queue_stmt->execute();
        $queue_stmt->close();
        return true;
    }
    return false;
}

$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;
}

$send_email = isset($_POST['send_email']) ? $_POST['send_email'] === '1' : true;

try {
    $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();
    $stmt->close();

    if (!$consultation) {
        throw new Exception("Consultation not found with ID: " . $consultation_id);
    }

    $recipient_email = !empty($consultation['user_email']) ? $consultation['user_email'] : $consultation['consultation_email'];

    $hasVerificationColumn = false;
    $verifyColResult = $connection->query("SHOW COLUMNS FROM consultations LIKE 'verification_status'");
    if ($verifyColResult && $verifyColResult->num_rows > 0) {
        $hasVerificationColumn = true;
    }

    $updateSql = $hasVerificationColumn
        ? "UPDATE consultations SET status = 'declined', verification_status = 'declined', updated_at = NOW() WHERE id = ?"
        : "UPDATE consultations SET status = 'declined', updated_at = NOW() WHERE id = ?";
    $update_stmt = $connection->prepare($updateSql);
    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);
    }
    $update_stmt->close();

    $to = $recipient_email;
    $subject = "Consultation Request Status Update - Interior Design Solutions";

    $name = trim(($consultation['first_name'] ?? '') . ' ' . ($consultation['last_name'] ?? ''));
    $consultation_type = ucfirst(str_replace('_', ' ', (string)($consultation['consultation_type'] ?? '')));
    $preferred_date = !empty($consultation['preferred_date']) ? date('F d, Y', strtotime($consultation['preferred_date'])) : 'N/A';

    $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; }
        .next-steps { background: #fef3c7; padding: 20px; border-radius: 8px; border-left: 4px solid #d4a574; }
    </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><strong>Consultation Type:</strong> " . htmlspecialchars($consultation_type) . "</div>
                    <div><strong>Preferred Date:</strong> " . 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.</p>
                <p>Best regards,<br><strong>Interior Design Solutions Team</strong></p>
            </div>
        </div>
    </body></html>";

    $email_sent = false;
    $email_error = null;

    if ($send_email) {
        $mailService = new DirectSMTPService();
        $mailResult = $mailService->sendEmail($to, $subject, $message, true);
        if (is_array($mailResult) && !empty($mailResult['success'])) {
            $email_sent = true;
        } else {
            $email_error = is_array($mailResult) ? ($mailResult['message'] ?? 'Unknown mail error') : 'Unknown mail error';
            queueEmail($connection, $consultation_id, $to, $subject, $message, 'decline', $email_error);
        }
    }

    $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();
        $notif_stmt->close();
    }

    $responseMessage = 'Consultation declined successfully.';
    if ($send_email) {
        $responseMessage = $email_sent
            ? ('Consultation declined and email sent to ' . htmlspecialchars($to))
            : 'Consultation declined. Email queued for delivery.';
    }

    echo json_encode([
        'success' => true,
        'message' => $responseMessage,
        'email_sent' => $email_sent,
        'notification_type' => 'decline',
        'recipient' => htmlspecialchars($name),
        '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();
    }
}
?>
