<?php
require_once __DIR__ . '/../../../../helpers/response.php';
require_once __DIR__ . '/../../../../helpers/validation.php';
require_once __DIR__ . '/../../../Middleware/AuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class QuotationRequestController {
    
    public function create() {
        // Authenticate customer
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $errors = validateRequired($data, ['vendor_id', 'request_type']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }

        $db = Database::getInstance();

        // Optional: If maid_id is provided, verify it exists
        $maidId = !empty($data['maid_id']) ? $data['maid_id'] : null;
        if ($maidId) {
            $stmt = $db->prepare("SELECT id FROM maids WHERE id = ?");
            $stmt->execute([$maidId]);
            if (!$stmt->fetch()) {
                sendError('Validation failed', ['maid_id' => 'Selected maid does not exist'], 422);
            }
        }

        // Verify vendor exists
        $stmt = $db->prepare("SELECT id FROM vendors WHERE id = ?");
        $stmt->execute([$data['vendor_id']]);
        if (!$stmt->fetch()) {
            sendError('Validation failed', ['vendor_id' => 'Selected vendor does not exist'], 422);
        }

        $db->beginTransaction();
        try {
            $stmt = $db->prepare("
                INSERT INTO quotation_requests (
                    customer_id, vendor_id, maid_id, request_type, 
                    service_model_id, accommodation_type_id, preferred_nationality_id, 
                    start_date, duration_months, work_days, city_id, 
                    number_of_helpers, estimated_monthly_payment, estimated_total_value, 
                    additional_notes, status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
            ");

            $preferredNationalityId = !empty($data['preferred_nationality_id']) ? $data['preferred_nationality_id'] : null;
            if (empty($preferredNationalityId) && !empty($data['preferred_nationality_ids'])) {
                $preferredNationalityId = $data['preferred_nationality_ids'][0];
            }

            $stmt->execute([
                $customerId,
                $data['vendor_id'],
                $maidId,
                $data['request_type'],
                !empty($data['service_model_id']) ? $data['service_model_id'] : null,
                !empty($data['accommodation_type_id']) ? $data['accommodation_type_id'] : null,
                $preferredNationalityId,
                !empty($data['start_date']) ? $data['start_date'] : date('Y-m-d', strtotime('+1 day')),
                !empty($data['duration_months']) ? intval($data['duration_months']) : 12,
                !empty($data['work_days']) ? intval($data['work_days']) : null,
                !empty($data['city_id']) ? $data['city_id'] : null,
                !empty($data['number_of_helpers']) ? intval($data['number_of_helpers']) : 1,
                !empty($data['estimated_monthly_payment']) ? floatval($data['estimated_monthly_payment']) : null,
                !empty($data['estimated_total_value']) ? floatval($data['estimated_total_value']) : null,
                !empty($data['additional_notes']) ? $data['additional_notes'] : null
            ]);

            $requestId = $db->lastInsertId();

            // Specialties
            if (!empty($data['specialty_ids']) && is_array($data['specialty_ids'])) {
                $stmtSpec = $db->prepare("INSERT INTO quotation_request_specialties (quotation_request_id, specialty_id) VALUES (?, ?)");
                foreach ($data['specialty_ids'] as $specId) {
                    $stmtSpec->execute([$requestId, $specId]);
                }
            }

            // Skills
            if (!empty($data['skill_ids']) && is_array($data['skill_ids'])) {
                $stmtSkill = $db->prepare("INSERT INTO quotation_request_skills (quotation_request_id, skill_id) VALUES (?, ?)");
                foreach ($data['skill_ids'] as $skillId) {
                    $stmtSkill->execute([$requestId, $skillId]);
                }
            }

            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to submit quotation request: ' . $e->getMessage(), [], 500);
        }

        // Fetch inserted request with details
        $stmt = $db->prepare("
            SELECT qr.*, v.agency_name as vendor_name, m.full_name as maid_name
            FROM quotation_requests qr
            LEFT JOIN vendors v ON qr.vendor_id = v.id
            LEFT JOIN maids m ON qr.maid_id = m.id
            WHERE qr.id = ?
        ");
        $stmt->execute([$requestId]);
        $requestDetails = $stmt->fetch();

        sendResponse($requestDetails, 'Quotation request submitted successfully', 201);
    }

    public function index($requestType = null) {
        // Authenticate customer
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $db = Database::getInstance();
        $status = $_GET['status'] ?? null;
        
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $countSql = "
            SELECT COUNT(*)
            FROM quotation_requests qr
            WHERE qr.customer_id = ?
        ";
        $countParams = [$customerId];
        if ($status) {
            $countSql .= " AND qr.status = ?";
            $countParams[] = $status;
        }
        if ($requestType) {
            $countSql .= " AND qr.request_type = ?";
            $countParams[] = $requestType;
        }
        $totalStmt = $db->prepare($countSql);
        $totalStmt->execute($countParams);
        $total = (int) $totalStmt->fetchColumn();

        $sql = "
            SELECT qr.*, v.agency_name as vendor_name, m.full_name as maid_name
            FROM quotation_requests qr
            LEFT JOIN vendors v ON qr.vendor_id = v.id
            LEFT JOIN maids m ON qr.maid_id = m.id
            WHERE qr.customer_id = ?
        ";
        $params = [$customerId];
        
        if ($status) {
            $sql .= " AND qr.status = ?";
            $params[] = $status;
        }
        if ($requestType) {
            $sql .= " AND qr.request_type = ?";
            $params[] = $requestType;
        }
        
        $sql .= " ORDER BY qr.created_at DESC LIMIT " . intval($limit) . " OFFSET " . intval($offset);
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $requests = $stmt->fetchAll();

        foreach ($requests as &$r) {
            // Dynamic UI enrichment for status label & description
            if ($r['status'] === 'pending') {
                $r['status_label'] = 'UNDER REVIEW';
                $r['status_description'] = 'Vendor reviewing availability';
            } elseif ($r['status'] === 'quoted') {
                $r['status_label'] = 'ACTION REQUIRED';
                $r['status_description'] = 'Review and approve vendor quote';
            } elseif ($r['status'] === 'accepted') {
                // Check if a contract is pending verification
                $stmtContract = $db->prepare("SELECT status FROM contracts WHERE quotation_request_id = ? LIMIT 1");
                $stmtContract->execute([$r['id']]);
                $contractStatus = $stmtContract->fetchColumn();
                
                if ($contractStatus === 'pending') {
                    $r['status_label'] = 'VERIFICATION';
                    $r['status_description'] = 'Contract generation in progress. Our legal department is currently finalizing terms.';
                } else {
                    $r['status_label'] = 'APPROVED';
                    $r['status_description'] = 'Request approved and contract ready.';
                }
            } elseif ($r['status'] === 'declined') {
                $r['status_label'] = 'DECLINED';
                $r['status_description'] = 'Vendor declined the request.';
            } elseif ($r['status'] === 'cancelled') {
                $r['status_label'] = 'CANCELLED';
                $r['status_description'] = 'You cancelled the request.';
            } else {
                $r['status_label'] = strtoupper($r['status']);
                $r['status_description'] = '';
            }

            // Format ID matching visual design
            $r['formatted_id'] = 'RQ-' . str_pad($r['id'], 6, '0', STR_PAD_LEFT);
        }

        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Quotation requests loaded', ['requests' => $requests], $pagination);
    }

    public function indexSpecific() {
        $this->index('specific_maid');
    }

    public function indexGeneral() {
        $this->index('general_vendor');
    }

    public function show($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT qr.*, 
                   v.agency_name as vendor_name, v.logo as vendor_logo, v.is_verified as vendor_verified,
                   v.email as vendor_email, v.phone as vendor_phone, v.address as vendor_address,
                   v.latitude as vendor_latitude, v.longitude as vendor_longitude,
                   m.full_name as maid_name, m.profile_image as maid_image,
                   sm.name_en as service_model_name,
                   pn.name_en as preferred_nationality_name,
                   c.name_en as city_name
            FROM quotation_requests qr
            LEFT JOIN vendors v ON qr.vendor_id = v.id
            LEFT JOIN maids m ON qr.maid_id = m.id
            LEFT JOIN service_models sm ON qr.service_model_id = sm.id
            LEFT JOIN nationalities pn ON qr.preferred_nationality_id = pn.id
            LEFT JOIN cities c ON qr.city_id = c.id
            WHERE qr.id = ? AND qr.customer_id = ?
            LIMIT 1
        ");
        $stmt->execute([$id, $customerId]);
        $req = $stmt->fetch();

        if (!$req) {
            sendError('Quotation request not found', [], 404);
        }

        // Enrichment for status labels & descriptions matching the UI
        if ($req['status'] === 'pending') {
            $req['status_label'] = 'UNDER REVIEW';
            $req['status_description'] = 'Vendor reviewing availability';
        } elseif ($req['status'] === 'quoted') {
            $req['status_label'] = 'ACTION REQUIRED';
            $req['status_description'] = 'Review and approve vendor quote';
        } elseif ($req['status'] === 'accepted') {
            $stmtContract = $db->prepare("SELECT status FROM contracts WHERE quotation_request_id = ? LIMIT 1");
            $stmtContract->execute([$req['id']]);
            $contractStatus = $stmtContract->fetchColumn();
            
            if ($contractStatus === 'pending') {
                $req['status_label'] = 'VERIFICATION';
                $req['status_description'] = 'Contract generation in progress. Our legal department is currently finalizing terms.';
            } else {
                $req['status_label'] = 'APPROVED';
                $req['status_description'] = 'Request approved and contract ready.';
            }
        } elseif ($req['status'] === 'declined') {
            $req['status_label'] = 'DECLINED';
            $req['status_description'] = 'Vendor declined the request.';
        } elseif ($req['status'] === 'cancelled') {
            $req['status_label'] = 'CANCELLED';
            $req['status_description'] = 'You cancelled the request.';
        } else {
            $req['status_label'] = strtoupper($req['status']);
            $req['status_description'] = '';
        }

        // Format ID
        $req['formatted_id'] = 'RQ-' . str_pad($req['id'], 6, '0', STR_PAD_LEFT);

        // Fetch specialties
        $stmtSpec = $db->prepare("
            SELECT s.name_en 
            FROM quotation_request_specialties qrs
            JOIN specialties s ON qrs.specialty_id = s.id
            WHERE qrs.quotation_request_id = ?
        ");
        $stmtSpec->execute([$id]);
        $req['specialties'] = $stmtSpec->fetchAll(PDO::FETCH_COLUMN) ?: [];

        // Fetch skills
        $stmtSkill = $db->prepare("
            SELECT s.name_en 
            FROM quotation_request_skills qrs
            JOIN skills s ON qrs.skill_id = s.id
            WHERE qrs.quotation_request_id = ?
        ");
        $stmtSkill->execute([$id]);
        $req['skills'] = $stmtSkill->fetchAll(PDO::FETCH_COLUMN) ?: [];

        // Rating & Reviews count for the vendor
        $stmtRating = $db->prepare("
            SELECT COALESCE(AVG(rating), 5.0) as rating, COUNT(id) as reviews_count 
            FROM reviews 
            WHERE vendor_id = ? AND status = 'approved'
        ");
        $stmtRating->execute([$req['vendor_id']]);
        $ratingDetails = $stmtRating->fetch();
        $req['vendor_rating'] = floatval($ratingDetails['rating']);
        $req['vendor_reviews_count'] = intval($ratingDetails['reviews_count']);

        // Staff count for the vendor
        $stmtStaff = $db->prepare("SELECT COUNT(*) FROM maids WHERE vendor_id = ? AND status = 'published'");
        $stmtStaff->execute([$req['vendor_id']]);
        $req['vendor_staff_count'] = intval($stmtStaff->fetchColumn());

        // Fetch associated quotation if one exists
        $stmtQuote = $db->prepare("
            SELECT q.* 
            FROM quotations q
            WHERE q.quotation_request_id = ? AND q.customer_id = ?
            ORDER BY q.id DESC
            LIMIT 1
        ");
        $stmtQuote->execute([$id, $customerId]);
        $quotation = $stmtQuote->fetch();

        if ($quotation) {
            // Format ID and Inclusions
            $quotation['formatted_id'] = 'QH-' . str_pad($quotation['id'], 6, '0', STR_PAD_LEFT);
            $stmtInc = $db->prepare("SELECT title, description, is_included FROM quotation_inclusions WHERE quotation_id = ?");
            $stmtInc->execute([$quotation['id']]);
            $inclusions = $stmtInc->fetchAll();
            
            foreach ($inclusions as &$inc) {
                $inc['is_included'] = (bool)$inc['is_included'];
            }
            
            $quotation['inclusions'] = $inclusions;
            $req['quotation'] = $quotation;
        } else {
            $req['quotation'] = null;
        }

        // Generate Timeline matching the design perfectly
        $timeline = [];
        $createdAt = strtotime($req['created_at']);
        $serviceType = $req['service_model_name'] ?? 'Maid';
        
        // Step 1: Request Sent
        $timeline[] = [
            'title' => 'Request Sent',
            'description' => "Your request for " . strtolower($serviceType) . " services was sent on " . date('M d', $createdAt) . ".",
            'completed' => true,
            'time' => date('h:i A', $createdAt),
            'date' => date('Y-m-d', $createdAt)
        ];

        // Step 2 & 3: Progress
        if ($req['status'] === 'pending') {
            $timeline[] = [
                'title' => 'Vendor Reviewing',
                'description' => "{$req['vendor_name']} is reviewing your request and availability. Estimated response: 24h.",
                'completed' => false,
                'time' => null,
                'date' => null
            ];
            $timeline[] = [
                'title' => 'Request Status',
                'description' => "You'll be notified once the request status is ready.",
                'completed' => false,
                'time' => null,
                'date' => null
            ];
        } elseif ($req['status'] === 'quoted' || $req['status'] === 'accepted') {
            $updatedAt = $req['updated_at'] ? strtotime($req['updated_at']) : time();
            $timeline[] = [
                'title' => 'Vendor Reviewing',
                'description' => "{$req['vendor_name']} reviewed your request and approved the availability.",
                'completed' => true,
                'time' => date('h:i A', $updatedAt),
                'date' => date('Y-m-d', $updatedAt)
            ];
            $timeline[] = [
                'title' => 'Request Approved',
                'description' => "The contract has been approved by vendor and is ready for you to contact them for next steps.",
                'completed' => true,
                'time' => date('h:i A', $updatedAt),
                'date' => date('Y-m-d', $updatedAt)
            ];
        } elseif ($req['status'] === 'cancelled' || $req['status'] === 'declined') {
            $updatedAt = $req['updated_at'] ? strtotime($req['updated_at']) : time();
            $timeline[] = [
                'title' => 'Request Closed',
                'description' => "Your request has been closed (status: " . $req['status'] . ").",
                'completed' => true,
                'time' => date('h:i A', $updatedAt),
                'date' => date('Y-m-d', $updatedAt)
            ];
        }

        $req['timeline'] = $timeline;

        sendResponse($req, 'Quotation request details loaded successfully');
    }

    public function cancel($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $db = Database::getInstance();
        
        $stmt = $db->prepare("SELECT id, status FROM quotation_requests WHERE id = ? AND customer_id = ?");
        $stmt->execute([$id, $customerId]);
        $request = $stmt->fetch();

        if (!$request) {
            sendError('Quotation request not found', [], 404);
        }

        if ($request['status'] === 'cancelled' || $request['status'] === 'quoted' || $request['status'] === 'accepted') {
            sendError('Cannot cancel quotation request in its current state', [], 400);
        }

        $stmt = $db->prepare("UPDATE quotation_requests SET status = 'cancelled' WHERE id = ?");
        $stmt->execute([$id]);

        sendResponse([], 'Quotation request cancelled successfully');
    }
}
