<?php
/**
 * AUTO TESTER - Walk-in Inspections API
 * Handles walk-in inspection requests for main centers
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../database/functions/Database.php';

class WalkinInspections {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create walk-in inspection request
     */
    public function createWalkinRequest($data) {
        try {
            // Validate required fields
            $required = ['inspection_type_id', 'customer_name', 'customer_phone', 'vehicle_make', 'vehicle_model', 'vehicle_year'];
            foreach ($required as $field) {
                if (!isset($data[$field]) || $data[$field] === '') {
                    return ['success' => false, 'message' => "Field $field is required"];
                }
            }
            
            // Generate unique request number
            $requestNumber = $this->generateRequestNumber();
            
            // Create customer record (walk-in customers don't need full accounts)
            $customerId = $this->createWalkinCustomer($data);
            
            // Insert inspection request
            $stmt = $this->db->prepare("
                INSERT INTO inspection_requests_enhanced 
                (request_number, customer_id, inspection_type_id, vehicle_make, vehicle_model,
                 vehicle_year, vehicle_color, vehicle_vin, vehicle_plate_number, vehicle_mileage,
                 vehicle_engine_type, vehicle_transmission, preferred_date, preferred_time,
                 location_type, special_instructions, urgency_level, quoted_price, final_price,
                 payment_status, payment_method, current_stage, current_status, priority_level,
                 source, ip_address, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'registration', 'submitted', 'high', ?, ?, NOW())
            ");
            
            $result = $stmt->execute([
                $requestNumber,
                $customerId,
                $data['inspection_type_id'],
                $data['vehicle_make'],
                $data['vehicle_model'],
                $data['vehicle_year'],
                $data['vehicle_color'] ?? '',
                $data['vehicle_vin'] ?? '',
                $data['vehicle_plate_number'] ?? '',
                $data['vehicle_mileage'] ?? 0,
                $data['vehicle_engine_type'] ?? 'gasoline',
                $data['vehicle_transmission'] ?? 'manual',
                date('Y-m-d'), // Today's date for walk-in
                date('H:i:s'), // Current time
                'center',
                $data['special_instructions'] ?? '',
                $data['urgency_level'] ?? 'normal',
                $data['quoted_price'],
                $data['quoted_price'], // Final price same as quoted for walk-in
                'pending',
                $data['payment_method'],
                'high', // High priority for walk-ins
                'walk_in',
                $_SERVER['REMOTE_ADDR'] ?? ''
            ]);
            
            if ($result) {
                $requestId = $this->db->lastInsertId();
                
                // Auto-assign to available inspector
                $this->autoAssignInspector($requestId);
                
                // Send real-time notifications
                $this->sendInspectorNotifications($requestId);
                
                return [
                    'success' => true, 
                    'message' => 'Walk-in request created successfully',
                    'request_id' => $requestId,
                    'request_number' => $requestNumber
                ];
            } else {
                return ['success' => false, 'message' => 'Failed to create walk-in request'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Create walk-in customer record
     */
    private function createWalkinCustomer($data) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO users 
                (username, email, phone, full_name, role, status, is_main_center, created_at)
                VALUES (?, ?, ?, ?, 'walk_in_customer', 'active', 1, NOW())
            ");
            
            $username = 'walkin_' . time() . '_' . rand(1000, 9999);
            $email = $data['customer_email'] ?? null;
            if (!$email) {
                $email = 'walkin_' . time() . '@autotester.com';
            }
            
            $stmt->execute([
                $username,
                $email,
                $data['customer_phone'],
                $data['customer_name']
            ]);
            
            return $this->db->lastInsertId();
            
        } catch (Exception $e) {
            throw new Exception('Failed to create walk-in customer: ' . $e->getMessage());
        }
    }
    
    /**
     * Auto-assign inspector to walk-in request
     */
    private function autoAssignInspector($requestId) {
        try {
            // Get available inspectors (not currently working on high-priority tasks)
            $stmt = $this->db->prepare("
                SELECT u.id, u.full_name
                FROM users u
                WHERE u.role = 'inspector' 
                AND u.status = 'active'
                AND u.id NOT IN (
                    SELECT DISTINCT ir.assigned_inspector_id
                    FROM inspection_requests_enhanced ir
                    WHERE ir.current_status = 'in_progress'
                    AND ir.priority_level = 'high'
                    AND ir.assigned_inspector_id IS NOT NULL
                )
                ORDER BY RAND()
                LIMIT 1
            ");
            $stmt->execute();
            $inspector = $stmt->fetch();
            
            if ($inspector) {
                // Assign inspector
                $stmt = $this->db->prepare("
                    UPDATE inspection_requests_enhanced 
                    SET assigned_inspector_id = ?, assigned_at = NOW(), current_stage = 'inspection_execution'
                    WHERE id = ?
                ");
                $stmt->execute([$inspector['id'], $requestId]);
                
                return $inspector['id'];
            }
            
            return null;
            
        } catch (Exception $e) {
            error_log("Error auto-assigning inspector: " . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Send real-time notifications to inspectors
     */
    private function sendInspectorNotifications($requestId) {
        try {
            // Get request details
            $stmt = $this->db->prepare("
                SELECT ire.*, it.type_name_ar, u.full_name as customer_name
                FROM inspection_requests_enhanced ire
                JOIN inspection_types it ON ire.inspection_type_id = it.id
                JOIN users u ON ire.customer_id = u.id
                WHERE ire.id = ?
            ");
            $stmt->execute([$requestId]);
            $request = $stmt->fetch();
            
            if (!$request) return;
            
            // Get all inspectors for notification
            $stmt = $this->db->prepare("
                SELECT id, full_name FROM users 
                WHERE role = 'inspector' AND status = 'active'
            ");
            $stmt->execute();
            $inspectors = $stmt->fetchAll();
            
            // Create notification message
            $title = 'Walk-in Request - High Priority';
            $message = "New walk-in request: {$request['type_name_ar']} for {$request['vehicle_make']} {$request['vehicle_model']} - Customer: {$request['customer_name']}";
            
            foreach ($inspectors as $inspector) {
                $stmt = $this->db->prepare("
                    INSERT INTO workflow_notifications 
                    (inspection_request_id, notification_type, recipient_id, recipient_role,
                     title_ar, title_en, message_ar, message_en, channels, priority, requires_action, created_at)
                    VALUES (?, 'assignment', ?, 'inspector', ?, ?, ?, ?, 'in_app', 'high', 1, NOW())
                ");
                
                $stmt->execute([
                    $requestId,
                    $inspector['id'],
                    $title,
                    'Walk-in Request - High Priority',
                    $message,
                    "New walk-in request: {$request['type_name_en']} for {$request['vehicle_make']} {$request['vehicle_model']}"
                ]);
            }
            
        } catch (Exception $e) {
            error_log("Error sending inspector notifications: " . $e->getMessage());
        }
    }
    
    /**
     * Get walk-in requests for inspectors
     */
    public function getWalkinRequests() {
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    ire.*,
                    it.type_name_ar,
                    it.type_name_en,
                    it.estimated_duration_minutes,
                    it.base_price,
                    u.full_name as customer_name,
                    u.phone as customer_phone,
                    insp.full_name as inspector_name,
                    ws.stage_name_ar as current_stage_name
                FROM inspection_requests_enhanced ire
                JOIN inspection_types it ON ire.inspection_type_id = it.id
                JOIN users u ON ire.customer_id = u.id
                LEFT JOIN users insp ON ire.assigned_inspector_id = insp.id
                LEFT JOIN inspection_workflow_stages ws ON ire.current_stage = ws.stage_code
                WHERE ire.source = 'walk_in'
                AND ire.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                ORDER BY 
                    CASE WHEN ire.priority_level = 'high' AND ire.current_status = 'submitted' THEN 1 ELSE 2 END,
                    ire.created_at DESC
            ");
            $stmt->execute();
            $requests = $stmt->fetchAll();
            
            return ['success' => true, 'data' => $requests];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Get walk-in statistics for today
     */
    public function getWalkinStats() {
        try {
            $stmt = $this->db->prepare("
                SELECT 
                    COUNT(*) as total_walkins,
                    SUM(CASE WHEN current_status = 'completed' THEN 1 ELSE 0 END) as completed,
                    SUM(CASE WHEN current_status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
                    SUM(CASE WHEN current_status = 'submitted' THEN 1 ELSE 0 END) as pending,
                    SUM(final_price) as total_revenue,
                    AVG(CASE WHEN actual_duration_minutes IS NOT NULL THEN actual_duration_minutes END) as avg_duration
                FROM inspection_requests_enhanced 
                WHERE source = 'walk_in'
                AND DATE(created_at) = CURDATE()
            ");
            $stmt->execute();
            $stats = $stmt->fetch();
            
            return ['success' => true, 'data' => $stats];
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Update walk-in request status
     */
    public function updateWalkinStatus($requestId, $data) {
        try {
            // Get current request
            $stmt = $this->db->prepare("SELECT * FROM inspection_requests_enhanced WHERE id = ? AND source = 'walk_in'");
            $stmt->execute([$requestId]);
            $request = $stmt->fetch();
            
            if (!$request) {
                return ['success' => false, 'message' => 'Walk-in request not found'];
            }
            
            // Update status
            $updateFields = [];
            $updateValues = [];
            
            if (isset($data['current_status'])) {
                $updateFields[] = "current_status = ?";
                $updateValues[] = $data['current_status'];
                
                // Update timestamps based on status
                if ($data['current_status'] === 'in_progress' && !$request['started_at']) {
                    $updateFields[] = "started_at = NOW()";
                } elseif ($data['current_status'] === 'completed' && !$request['completed_at']) {
                    $updateFields[] = "completed_at = NOW()";
                }
            }
            
            if (isset($data['assigned_inspector_id'])) {
                $updateFields[] = "assigned_inspector_id = ?";
                $updateValues[] = $data['assigned_inspector_id'];
                $updateFields[] = "assigned_at = NOW()";
            }
            
            if (empty($updateFields)) {
                return ['success' => false, 'message' => 'No valid fields to update'];
            }
            
            $updateFields[] = "updated_at = NOW()";
            $updateValues[] = $requestId;
            
            $sql = "UPDATE inspection_requests_enhanced SET " . implode(', ', $updateFields) . " WHERE id = ?";
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute($updateValues);
            
            if ($result) {
                return ['success' => true, 'message' => 'Walk-in request updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update walk-in request'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Generate unique request number
     */
    private function generateRequestNumber() {
        $prefix = 'WALK';
        $date = date('Ym');
        $sequence = 1;
        
        // Get last sequence for today
        $stmt = $this->db->prepare("
            SELECT request_number FROM inspection_requests_enhanced 
            WHERE request_number LIKE ? AND source = 'walk_in'
            ORDER BY id DESC LIMIT 1
        ");
        $stmt->execute(["{$prefix}{$date}%"]);
        $lastRequest = $stmt->fetch();
        
        if ($lastRequest) {
            $lastSequence = intval(substr($lastRequest['request_number'], -4));
            $sequence = $lastSequence + 1;
        }
        
        return $prefix . $date . str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }
}

// API Endpoint Handler
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$walkin = new WalkinInspections();
$endpoint = $_GET['endpoint'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($endpoint) {
        case 'requests':
            if ($method === 'GET') {
                echo json_encode($walkin->getWalkinRequests());
            } elseif ($method === 'POST') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($walkin->createWalkinRequest($data));
            }
            break;
            
        case 'stats':
            if ($method === 'GET') {
                echo json_encode($walkin->getWalkinStats());
            }
            break;
            
        case 'status':
            if ($method === 'PUT') {
                $data = json_decode(file_get_contents('php://input'), true);
                echo json_encode($walkin->updateWalkinStatus($data['request_id'], $data));
            }
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Endpoint not found']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
?>
