<?php
/**
 * Utility Functions
 */
define('BASE_URL', '/routex');

class Utils {
    /**
     * Generate unique tracking code
     */
    public static function generateTrackingCode() {
        $prefix = 'ROU';
        $random = strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 11));
        return $prefix . $random;
    }

    /**
     * Sanitize input
     */
    public static function sanitize($input) {
        return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
    }

    /**
     * Validate email
     */
    public static function validateEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    }

    /**
     * Generate CSRF token
     */
    public static function generateCSRFToken() {
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }

    /**
     * Verify CSRF token
     */
    public static function verifyCSRFToken($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }

    /**
     * Format date
     */
    public static function formatDate($date, $format = 'M d, Y') {
        return date($format, strtotime($date));
    }

    /**
     * Format datetime
     */
    public static function formatDateTime($datetime, $format = 'M d, Y H:i') {
        return date($format, strtotime($datetime));
    }

    /**
     * Get status badge color
     */
    public static function getStatusColor($status) {
        $colors = [
            'pending' => 'bg-gray-100 text-gray-800',
            'picked_up' => 'bg-blue-100 text-blue-800',
            'in_transit' => 'bg-yellow-100 text-yellow-800',
            'out_for_delivery' => 'bg-purple-100 text-purple-800',
            'delivered' => 'bg-green-100 text-green-800',
            'cancelled' => 'bg-red-100 text-red-800'
        ];
        return $colors[$status] ?? 'bg-gray-100 text-gray-800';
    }

    /**
     * Get status label
     */
    public static function getStatusLabel($status) {
        $labels = [
            'pending' => 'Pending',
            'picked_up' => 'Picked Up',
            'in_transit' => 'In Transit',
            'out_for_delivery' => 'Out for Delivery',
            'delivered' => 'Delivered',
            'cancelled' => 'Cancelled'
        ];
        return $labels[$status] ?? ucfirst($status);
    }

    /**
     * Get service type label
     */
    public static function getServiceLabel($service) {
        $labels = [
            'air_freight' => 'Air Freight',
            'sea_freight' => 'Sea Freight',
            'road_transport' => 'Road Transport',
            'warehousing' => 'Warehousing'
        ];
        return $labels[$service] ?? ucfirst(str_replace('_', ' ', $service));
    }

    /**
     * Upload file
     */
    public static function uploadFile($file, $allowed_types = ['jpg', 'jpeg', 'png', 'gif']) {
        if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
            return ['success' => false, 'error' => 'No file uploaded'];
        }

        $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($file_ext, $allowed_types)) {
            return ['success' => false, 'error' => 'Invalid file type'];
        }

        if ($file['size'] > 5 * 1024 * 1024) { // 5MB limit
            return ['success' => false, 'error' => 'File too large'];
        }

        $upload_dir = UPLOAD_DIR;
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $filename = uniqid() . '.' . $file_ext;
        $filepath = $upload_dir . $filename;

        if (move_uploaded_file($file['tmp_name'], $filepath)) {
            return ['success' => true, 'filename' => $filename, 'path' => '/routex/uploads/' . $filename];
        }

        return ['success' => false, 'error' => 'Upload failed'];
    }

    /**
     * Delete file
     */
    public static function deleteFile($filename) {
        $filepath = UPLOAD_DIR . $filename;
        if (file_exists($filepath)) {
            return unlink($filepath);
        }
        return false;
    }

    /**
     * Redirect
     */
    public static function redirect($url) {
        header('Location: ' . $url);
        exit;
    }

    /**
     * JSON response
     */
    public static function jsonResponse($data, $status_code = 200) {
        header('Content-Type: application/json');
        http_response_code($status_code);
        echo json_encode($data);
        exit;
    }
}
