<?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 ContractController {
    
    public function index() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $limit = isset($_GET['limit']) ? max(1, intval($_GET['limit'])) : 10;
        $offset = ($page - 1) * $limit;

        $totalStmt = $db->prepare("SELECT COUNT(*) FROM contracts WHERE customer_id = ?");
        $totalStmt->execute([$customerId]);
        $total = (int) $totalStmt->fetchColumn();

        $stmt = $db->prepare("
            SELECT c.*, 
                   v.agency_name as vendor_name, v.logo as vendor_logo,
                   m.full_name as maid_name, m.profile_image as maid_image
            FROM contracts c
            LEFT JOIN vendors v ON c.vendor_id = v.id
            LEFT JOIN maids m ON c.maid_id = m.id
            WHERE c.customer_id = ?
            ORDER BY c.created_at DESC
            LIMIT " . intval($limit) . " OFFSET " . intval($offset) . "
        ");
        $stmt->execute([$customerId]);
        $contracts = $stmt->fetchAll();
        
        foreach ($contracts as &$contract) {
            $currency = $contract['currency'] ?: 'AED';
            $contract['monthly_salary_formatted'] = $currency . ' ' . number_format($contract['monthly_salary'], 2);
            $contract['total_amount_formatted'] = $currency . ' ' . number_format($contract['total_amount'], 2);
            $contract['period_formatted'] = date('M Y', strtotime($contract['start_date'])) . ' - ' . date('M Y', strtotime($contract['end_date']));
        }
        
        $pagination = [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'total_pages' => ceil($total / $limit)
        ];

        jsonResponse(true, 'Contracts loaded successfully', ['contracts' => $contracts], $pagination);
    }
    
    public function show($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        $stmt = $db->prepare("
            SELECT c.*, 
                   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, m.bio as maid_bio,
                   n.name_en as maid_nationality
            FROM contracts c
            LEFT JOIN vendors v ON c.vendor_id = v.id
            LEFT JOIN maids m ON c.maid_id = m.id
            LEFT JOIN nationalities n ON m.nationality_id = n.id
            WHERE c.id = ? AND c.customer_id = ?
            LIMIT 1
        ");
        $stmt->execute([$id, $customerId]);
        $contract = $stmt->fetch();
        
        if (!$contract) {
            sendError('Contract not found', [], 404);
        }
        
        // Formatting
        $currency = $contract['currency'] ?: 'AED';
        $contract['monthly_salary_formatted'] = $currency . ' ' . number_format($contract['monthly_salary'], 2);
        $contract['total_amount_formatted'] = $currency . ' ' . number_format($contract['total_amount'], 2);
        $contract['period_formatted'] = date('M Y', strtotime($contract['start_date'])) . ' - ' . date('M Y', strtotime($contract['end_date']));
        
        // History
        $stmtLogs = $db->prepare("SELECT status, note, created_at FROM contract_status_logs WHERE contract_id = ? ORDER BY created_at DESC");
        $stmtLogs->execute([$id]);
        $contract['status_history'] = $stmtLogs->fetchAll();
        
        sendResponse($contract, 'Contract details loaded successfully');
    }

    public function create() {
        $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', 'start_date', 'duration_months', 'monthly_salary', 'total_amount']);
        if (!empty($errors)) {
            sendError('Validation failed', $errors, 422);
        }
        
        $db = Database::getInstance();
        
        // Check vendor exists
        $stmt = $db->prepare("SELECT id FROM vendors WHERE id = ?");
        $stmt->execute([$data['vendor_id']]);
        if (!$stmt->fetch()) {
            sendError('Selected vendor does not exist', [], 422);
        }
        
        $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('Selected maid does not exist', [], 422);
            }
        }
        
        $quotationRequestId = !empty($data['quotation_request_id']) ? $data['quotation_request_id'] : null;
        if ($quotationRequestId) {
            $stmt = $db->prepare("SELECT id FROM quotation_requests WHERE id = ?");
            $stmt->execute([$quotationRequestId]);
            if (!$stmt->fetch()) {
                sendError('Selected quotation request does not exist', [], 422);
            }
        } else {
            // Satisfy NOT NULL fk on quotation_requests
            $db->beginTransaction();
            try {
                $stmt = $db->prepare("
                    INSERT INTO quotation_requests (
                        customer_id, vendor_id, maid_id, request_type, status, start_date, duration_months
                    ) VALUES (?, ?, ?, 'general_vendor', 'quoted', ?, ?)
                ");
                $stmt->execute([
                    $customerId,
                    $data['vendor_id'],
                    $maidId,
                    $data['start_date'],
                    intval($data['duration_months'])
                ]);
                $quotationRequestId = $db->lastInsertId();
                $db->commit();
            } catch (Exception $e) {
                $db->rollBack();
                sendError('Failed to initialize quotation request for contract', ['error' => $e->getMessage()], 500);
            }
        }
        
        $quotationId = !empty($data['quotation_id']) ? $data['quotation_id'] : null;
        if ($quotationId) {
            $stmt = $db->prepare("SELECT id FROM quotations WHERE id = ?");
            $stmt->execute([$quotationId]);
            if (!$stmt->fetch()) {
                sendError('Selected quotation does not exist', [], 422);
            }
        }
        
        $contractNumber = 'HL-CON-' . strtoupper(bin2hex(random_bytes(4)));
        $startDate = $data['start_date'];
        $duration = intval($data['duration_months']);
        $endDate = date('Y-m-d', strtotime("+" . $duration . " months", strtotime($startDate)));
        $monthlySalary = floatval($data['monthly_salary']);
        $totalAmount = floatval($data['total_amount']);
        $currency = !empty($data['currency']) ? $data['currency'] : 'AED';
        $terms = !empty($data['terms']) ? $data['terms'] : 'Standard domestic service agreement.';
        
        $db->beginTransaction();
        try {
            $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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)
            ");
            
            $stmt->execute([
                $quotationId,
                $quotationRequestId,
                $customerId,
                $data['vendor_id'],
                $maidId,
                $contractNumber,
                $startDate,
                $endDate,
                $duration,
                $monthlySalary,
                $totalAmount,
                $currency,
                $terms
            ]);
            
            $contractId = $db->lastInsertId();
            
            $stmt = $db->prepare("
                INSERT INTO contract_status_logs (contract_id, status, note) 
                VALUES (?, 'pending', 'Contract created by customer.')
            ");
            $stmt->execute([$contractId]);
            
            $db->commit();
            
            $stmt = $db->prepare("
                SELECT c.*, v.agency_name as vendor_name, m.full_name as maid_name
                FROM contracts c
                LEFT JOIN vendors v ON c.vendor_id = v.id
                LEFT JOIN maids m ON c.maid_id = m.id
                WHERE c.id = ?
            ");
            $stmt->execute([$contractId]);
            $contractDetails = $stmt->fetch();
            
            sendResponse($contractDetails, 'Contract created successfully', 201);
            
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to create contract', ['error' => $e->getMessage()], 500);
        }
    }
    
    public function sign($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        
        // Fetch contract and verify ownership
        $stmt = $db->prepare("SELECT * FROM contracts WHERE id = ? AND customer_id = ?");
        $stmt->execute([$id, $customerId]);
        $contract = $stmt->fetch();
        
        if (!$contract) {
            sendError('Contract not found', [], 404);
        }
        
        if ($contract['status'] !== 'pending') {
            sendError('Contract can only be signed if status is pending', [], 400);
        }
        
        if ($contract['signed_by_customer_at']) {
            sendError('You have already signed this contract', [], 400);
        }
        
        $db->beginTransaction();
        try {
            // Update customer signature timestamp
            $stmt = $db->prepare("UPDATE contracts SET signed_by_customer_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$id]);
            
            // Update associated quotation status to 'signed'
            if ($contract['quotation_id']) {
                $stmt = $db->prepare("UPDATE quotations SET status = 'signed' WHERE id = ?");
                $stmt->execute([$contract['quotation_id']]);
            }
            
            // Re-fetch contract to check if vendor has also signed
            $stmt = $db->prepare("SELECT signed_by_vendor_at FROM contracts WHERE id = ?");
            $stmt->execute([$id]);
            $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([$id]);
                
                // Set maid availability status to booked
                if ($contract['maid_id']) {
                    $stmt = $db->prepare("UPDATE maids SET availability_status = 'booked' WHERE id = ?");
                    $stmt->execute([$contract['maid_id']]);
                }
            }
            
            // Insert audit log
            $stmt = $db->prepare("
                INSERT INTO contract_status_logs (contract_id, status, note) 
                VALUES (?, ?, 'Contract signed by customer.')
            ");
            $stmt->execute([$id, $status]);
            
            $db->commit();
            sendResponse([], 'Contract signed successfully');
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to sign contract', ['error' => $e->getMessage()], 500);
        }
    }
    
    public function cancel($id) {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];
        
        $db = Database::getInstance();
        
        // Fetch contract and verify ownership
        $stmt = $db->prepare("SELECT * FROM contracts WHERE id = ? AND customer_id = ?");
        $stmt->execute([$id, $customerId]);
        $contract = $stmt->fetch();
        
        if (!$contract) {
            sendError('Contract not found', [], 404);
        }
        
        if (in_array($contract['status'], ['completed', 'cancelled', 'rejected'])) {
            sendError('Cannot cancel contract in its current state', [], 400);
        }
        
        $db->beginTransaction();
        try {
            $stmt = $db->prepare("UPDATE contracts SET status = 'cancelled' WHERE id = ?");
            $stmt->execute([$id]);
            
            // Return maid availability status to available
            if ($contract['maid_id']) {
                $stmt = $db->prepare("UPDATE maids SET availability_status = 'available' WHERE id = ?");
                $stmt->execute([$contract['maid_id']]);
            }
            
            // Insert status log
            $stmt = $db->prepare("
                INSERT INTO contract_status_logs (contract_id, status, note) 
                VALUES (?, 'cancelled', 'Contract cancelled by customer.')
            ");
            $stmt->execute([$id]);
            
            $db->commit();
            sendResponse([], 'Contract cancelled successfully');
        } catch (Exception $e) {
            $db->rollBack();
            sendError('Failed to cancel contract', ['error' => $e->getMessage()], 500);
        }
    }
}
