<?php
/**
 * API Response Utility for Zen Zone Spa API
 * Standardizes all API responses
 */

require_once __DIR__ . '/../config/security.php';

class Response {
    
    /**
     * Send success response
     * @param mixed $data
     * @param string $message
     * @param int $status_code
     */
    public static function success($data = null, $message = 'Success', $status_code = 200) {
        self::setHeaders($status_code);
        
        $response = [
            'success' => true,
            'message' => $message,
            'timestamp' => date('Y-m-d H:i:s'),
            'status_code' => $status_code
        ];
        
        if ($data !== null) {
            $response['data'] = $data;
        }
        
        echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    /**
     * Send error response
     * @param string $message
     * @param int $status_code
     * @param array $errors
     */
    public static function error($message = 'Error occurred', $status_code = 400, $errors = null) {
        self::setHeaders($status_code);
        
        $response = [
            'success' => false,
            'message' => $message,
            'timestamp' => date('Y-m-d H:i:s'),
            'status_code' => $status_code
        ];
        
        if ($errors !== null) {
            $response['errors'] = $errors;
        }
        
        echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    /**
     * Send validation error response
     * @param array $validation_errors
     */
    public static function validationError($validation_errors) {
        self::error('Validation failed', 422, $validation_errors);
    }
    
    /**
     * Send unauthorized response
     */
    public static function unauthorized($message = 'Unauthorized access') {
        self::error($message, 401);
    }
    
    /**
     * Send forbidden response
     */
    public static function forbidden($message = 'Access forbidden') {
        self::error($message, 403);
    }
    
    /**
     * Send not found response
     */
    public static function notFound($message = 'Resource not found') {
        self::error($message, 404);
    }
    
    /**
     * Send server error response
     */
    public static function serverError($message = 'Internal server error') {
        // In development, show the actual error message
        if (SecurityConfig::env('DEBUG_MODE', false)) {
            self::error($message, 500);
        } else {
            self::error('Internal server error', 500);
        }
    }
    
    /**
     * Send paginated response
     * @param array $data
     * @param int $total
     * @param int $page
     * @param int $per_page
     * @param string $message
     */
    public static function paginated($data, $total, $page = 1, $per_page = 20, $message = 'Success') {
        $total_pages = ceil($total / $per_page);
        
        $pagination = [
            'data' => $data,
            'pagination' => [
                'current_page' => (int)$page,
                'per_page' => (int)$per_page,
                'total_items' => (int)$total,
                'total_pages' => (int)$total_pages,
                'has_next' => $page < $total_pages,
                'has_prev' => $page > 1
            ]
        ];
        
        self::success($pagination, $message);
    }
    
    /**
     * Set HTTP headers
     * @param int $status_code
     */
    private static function setHeaders($status_code) {
        // Set HTTP status code
        http_response_code($status_code);
        
        // Set content type
        header('Content-Type: application/json; charset=utf-8');
        
        // CORS headers for mobile app
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        
        // Security headers
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: DENY');
        header('X-XSS-Protection: 1; mode=block');
    }
    
    /**
     * Handle OPTIONS requests for CORS
     */
    public static function handleCORS() {
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            self::setHeaders(200);
            exit;
        }
    }
    
    /**
     * Get request method
     */
    public static function getRequestMethod() {
        return $_SERVER['REQUEST_METHOD'];
    }
    
    /**
     * Get request body as array
     */
    public static function getRequestBody() {
        $input = file_get_contents('php://input');
        return json_decode($input, true) ?: [];
    }
    
    /**
     * Validate required fields
     * @param array $data
     * @param array $required_fields
     * @return array|null
     */
    public static function validateRequired($data, $required_fields) {
        $errors = [];
        
        foreach ($required_fields as $field) {
            if (!isset($data[$field]) || empty(trim($data[$field]))) {
                $errors[$field] = "The {$field} field is required";
            }
        }
        
        return empty($errors) ? null : $errors;
    }
} 