<?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 QuotationController {
    
    public function index() {
        $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 quotations q
            LEFT JOIN vendors v ON q.vendor_id = v.id
            LEFT JOIN maids m ON q.maid_id = m.id
            LEFT JOIN quotation_requests qr ON q.quotation_request_id = qr.id
            WHERE q.customer_id = ?
        ";
        $countParams = [$customerId];
        if ($status) {
            if ($status === 'active') {
                $countSql .= " AND q.status IN ('sent', 'accepted')";
            } elseif ($status === 'completed') {
                $countSql .= " AND q.status = 'accepted'";
            } elseif ($status === 'cancelled') {
                $countSql .= " AND q.status IN ('declined', 'expired')";
            } else {
                $countSql .= " AND q.status = ?";
                $countParams[] = $status;
            }
        }
        $totalStmt = $db->prepare($countSql);
        $totalStmt->execute($countParams);
        $total = (int) $totalStmt->fetchColumn();

        $sql = "
            SELECT q.*, 
                   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,
                   qr.start_date, qr.duration_months, qr.number_of_helpers,
                   qr.request_type,
                   sm.name_en as service_model_name,
                   at.name_en as accommodation_type_name
            FROM quotations q
            LEFT JOIN vendors v ON q.vendor_id = v.id
            LEFT JOIN maids m ON q.maid_id = m.id
            LEFT JOIN quotation_requests qr ON q.quotation_request_id = qr.id
            LEFT JOIN service_models sm ON qr.service_model_id = sm.id
            LEFT JOIN accommodation_types at ON qr.accommodation_type_id = at.id
            WHERE q.customer_id = ?
        ";
        $params = [$customerId];
        
        if ($status) {
            if ($status === 'active') {
                $sql .= " AND q.status IN ('sent', 'accepted')";
            } elseif ($status === 'completed') {
                $sql .= " AND q.status = 'accepted'";
            } elseif ($status === 'cancelled') {
                $sql .= " AND q.status IN ('declined', 'expired')";
            } else {
                $sql .= " AND q.status = ?";
                $params[] = $status;
            }
        }
        
        $sql .= " ORDER BY q.created_at DESC LIMIT " . intval($limit) . " OFFSET " . intval($offset);
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $quotations = $stmt->fetchAll();
        
        foreach ($quotations as &$q) {
            $q['formatted_id'] = 'QH-' . str_pad($q['id'], 6, '0', STR_PAD_LEFT);
            
            // Expiry calculations
            $q['hours_left'] = null;
            $q['is_expired'] = false;
            if ($q['valid_until']) {
                $validUntilTimestamp = strtotime($q['valid_until'] . ' 23:59:59');
                $secondsLeft = $validUntilTimestamp - time();
                $q['hours_left'] = max(0, ceil($secondsLeft / 3600));
                if ($secondsLeft < 0) {
                    $q['is_expired'] = true;
                }
            }
            
            // Rating & Reviews count
            $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([$q['vendor_id']]);
            $ratingDetails = $stmtRating->fetch();
            $q['vendor_rating'] = floatval($ratingDetails['rating']);
            $q['vendor_reviews_count'] = intval($ratingDetails['reviews_count']);
            
            // Staff count
            $stmtStaff = $db->prepare("SELECT COUNT(*) FROM maids WHERE vendor_id = ? AND status = 'published'");
            $stmtStaff->execute([$q['vendor_id']]);
            $q['vendor_staff_count'] = intval($stmtStaff->fetchColumn());
            
            // Money Formats
            $currency = $q['currency'] ?: 'AED';
            $q['base_salary_formatted'] = $currency . ' ' . number_format($q['base_salary'], 2);
            $q['visa_processing_formatted'] = $currency . ' ' . number_format($q['visa_processing'], 2);
            $q['health_insurance_formatted'] = $currency . ' ' . number_format($q['health_insurance'], 2);
            $q['service_fee_formatted'] = $currency . ' ' . number_format($q['service_fee'], 2);
            $q['total_amount_formatted'] = $currency . ' ' . number_format($q['total_amount'], 2);
            
            // Period Formatted
            if ($q['start_date'] && $q['duration_months']) {
                $startDate = strtotime($q['start_date']);
                $endDate = strtotime("+" . $q['duration_months'] . " months", $startDate);
                $q['period_formatted'] = date('M Y', $startDate) . ' - ' . date('M Y', $endDate);
            } else {
                $q['period_formatted'] = null;
            }
        }
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Quotations loaded successfully', ['quotations' => $quotations], $pagination);
    }

    public function show($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT q.*, 
                   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,
                   qr.start_date, qr.duration_months, qr.number_of_helpers,
                   qr.request_type,
                   sm.name_en as service_model_name,
                   at.name_en as accommodation_type_name
            FROM quotations q
            LEFT JOIN vendors v ON q.vendor_id = v.id
            LEFT JOIN maids m ON q.maid_id = m.id
            LEFT JOIN quotation_requests qr ON q.quotation_request_id = qr.id
            LEFT JOIN service_models sm ON qr.service_model_id = sm.id
            LEFT JOIN accommodation_types at ON qr.accommodation_type_id = at.id
            WHERE q.id = ? AND q.customer_id = ?
            LIMIT 1
        ");
        $stmt->execute([$id, $customerId]);
        $q = $stmt->fetch();
        
        if (!$q) {
            sendError('Quotation not found', [], 404);
        }
        
        // Format ID
        $q['formatted_id'] = 'QH-' . str_pad($q['id'], 6, '0', STR_PAD_LEFT);
        
        // Expiry calculations
        $q['hours_left'] = null;
        $q['is_expired'] = false;
        if ($q['valid_until']) {
            $validUntilTimestamp = strtotime($q['valid_until'] . ' 23:59:59');
            $secondsLeft = $validUntilTimestamp - time();
            $q['hours_left'] = max(0, ceil($secondsLeft / 3600));
            if ($secondsLeft < 0) {
                $q['is_expired'] = true;
            }
        }
        
        // Rating & Reviews count
        $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([$q['vendor_id']]);
        $ratingDetails = $stmtRating->fetch();
        $q['vendor_rating'] = floatval($ratingDetails['rating']);
        $q['vendor_reviews_count'] = intval($ratingDetails['reviews_count']);
        
        // Staff count
        $stmtStaff = $db->prepare("SELECT COUNT(*) FROM maids WHERE vendor_id = ? AND status = 'published'");
        $stmtStaff->execute([$q['vendor_id']]);
        $q['vendor_staff_count'] = intval($stmtStaff->fetchColumn());
        
        // Money Formats
        $currency = $q['currency'] ?: 'AED';
        $q['base_salary_formatted'] = $currency . ' ' . number_format($q['base_salary'], 2);
        $q['visa_processing_formatted'] = $currency . ' ' . number_format($q['visa_processing'], 2);
        $q['health_insurance_formatted'] = $currency . ' ' . number_format($q['health_insurance'], 2);
        $q['service_fee_formatted'] = $currency . ' ' . number_format($q['service_fee'], 2);
        $q['total_amount_formatted'] = $currency . ' ' . number_format($q['total_amount'], 2);
        
        // Period Formatted
        if ($q['start_date'] && $q['duration_months']) {
            $startDate = strtotime($q['start_date']);
            $endDate = strtotime("+" . $q['duration_months'] . " months", $startDate);
            $q['period_formatted'] = date('M Y', $startDate) . ' - ' . date('M Y', $endDate);
        } else {
            $q['period_formatted'] = null;
        }
        
        // Inclusions
        $stmtInclusions = $db->prepare("SELECT title, description, is_included FROM quotation_inclusions WHERE quotation_id = ?");
        $stmtInclusions->execute([$id]);
        $inclusions = $stmtInclusions->fetchAll();
        
        if (empty($inclusions)) {
            $inclusions = [
                [
                    'title' => 'Background Checks',
                    'description' => 'Full criminal and professional history verified.',
                    'is_included' => true
                ],
                [
                    'title' => 'Medical Coverage',
                    'description' => 'Premium inpatient and outpatient insurance.',
                    'is_included' => true
                ],
                [
                    'title' => 'Replacement Guarantee',
                    'description' => 'Free replacement within the first 90 days.',
                    'is_included' => true
                ]
            ];
        }
        $q['inclusions'] = $inclusions;
        
        sendResponse($q, 'Quotation details loaded successfully');
    }
    
    public function action($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;
        
        $errors = validateRequired($data, ['status']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }
        
        $status = $data['status'];
        if (!in_array($status, ['accepted', 'declined'])) {
            sendError('Invalid status. Must be accepted or declined.', [], 422);
        }
        
        $db = Database::getInstance();
        
        // Fetch quotation and verify ownership
        $stmt = $db->prepare("SELECT * FROM quotations WHERE id = ? AND customer_id = ?");
        $stmt->execute([$id, $customerId]);
        $quotation = $stmt->fetch();
        
        if (!$quotation) {
            sendError('Quotation not found', [], 404);
        }
        
        if ($quotation['status'] !== 'sent') {
            sendError('Quotation can only be updated if status is sent', [], 400);
        }
        
        $db->beginTransaction();
        try {
            // Update quotation status
            $stmt = $db->prepare("UPDATE quotations SET status = ?, accepted_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$status, $id]);
            
            // Also update the original quotation request status to accepted/declined
            $stmt = $db->prepare("UPDATE quotation_requests SET status = ? WHERE id = ?");
            $stmt->execute([$status, $quotation['quotation_request_id']]);
            
            if ($status === 'accepted') {
                // Pre-generate a contract number
                $contractNumber = 'HL-CON-' . strtoupper(bin2hex(random_bytes(4)));
                
                // Fetch the start_date and duration_months from quotation_request
                $stmt = $db->prepare("SELECT start_date, duration_months FROM quotation_requests WHERE id = ?");
                $stmt->execute([$quotation['quotation_request_id']]);
                $qRequest = $stmt->fetch();
                
                $startDate = !empty($qRequest['start_date']) ? $qRequest['start_date'] : date('Y-m-d');
                $duration = !empty($qRequest['duration_months']) ? $qRequest['duration_months'] : 12;
                $endDate = date('Y-m-d', strtotime("+$duration months", strtotime($startDate)));
                
                // Create a dynamic contract record
                $stmt = $db->prepare("
                    INSERT INTO contracts (
                        quotation_id, quotation_request_id, customer_id, vendor_id, maid_id,
                        contract_number, start_date, end_date, duration_months, monthly_salary,
                        total_amount, currency, status, terms
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'AED', 'pending', ?)
                ");
                
                $terms = "Standard domestic service agreement for " . ($quotation['maid_id'] ? 'selected helper' : 'requested personnel') . " as per approved quotation HL-QOT-{$id}.";
                
                $stmt->execute([
                    $id,
                    $quotation['quotation_request_id'],
                    $customerId,
                    $quotation['vendor_id'],
                    $quotation['maid_id'],
                    $contractNumber,
                    $startDate,
                    $endDate,
                    $duration,
                    $quotation['base_salary'],
                    $quotation['total_amount'],
                    $terms
                ]);
            }
            
            $db->commit();
            sendResponse([], 'Quotation processed successfully');
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to process quotation', ['error' => $e->getMessage()], 500);
        }
    }

    public function sign($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        
        // Find associated contract
        $stmt = $db->prepare("SELECT id FROM contracts WHERE quotation_id = ? AND customer_id = ? LIMIT 1");
        $stmt->execute([$id, $customerId]);
        $contractId = $stmt->fetchColumn();
        
        if (!$contractId) {
            sendError('Associated contract not found', [], 404);
        }
        
        $db->beginTransaction();
        try {
            // Update customer signature timestamp
            $stmt = $db->prepare("UPDATE contracts SET signed_by_customer_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$contractId]);
            
            // Re-fetch contract to get maid and vendor signature
            $stmt = $db->prepare("SELECT signed_by_vendor_at, maid_id FROM contracts WHERE id = ?");
            $stmt->execute([$contractId]);
            $updated = $stmt->fetch();
            
            $status = 'pending';
            if ($updated['signed_by_vendor_at']) {
                $status = 'active';
                $stmt = $db->prepare("UPDATE contracts SET status = 'active' WHERE id = ?");
                $stmt->execute([$contractId]);
                
                // Set maid availability status to booked
                if ($updated['maid_id']) {
                    $stmt = $db->prepare("UPDATE maids SET availability_status = 'booked' WHERE id = ?");
                    $stmt->execute([$updated['maid_id']]);
                }
            }
            
            // Update quotation status to signed
            $stmt = $db->prepare("UPDATE quotations SET status = 'signed' WHERE id = ?");
            $stmt->execute([$id]);
            
            // Insert audit log
            $stmt = $db->prepare("
                INSERT INTO contract_status_logs (contract_id, status, note) 
                VALUES (?, ?, 'Contract signed by customer via quotation.')
            ");
            $stmt->execute([$contractId, $status]);
            
            $db->commit();
            sendResponse([], 'Contract signed successfully and quotation status set to signed');
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to sign contract', ['error' => $e->getMessage()], 500);
        }
    }
}
