<?php
/**
 * Response Handler for API
 * 
 * This class standardizes API responses with consistent formatting.
 */

class Response {
    /**
     * Send a successful response
     * 
     * @param mixed $data The data to send
     * @param string $message Optional success message
     * @param int $code HTTP status code (default 200)
     */
    public function success($data = null, $message = 'Success', $code = 200) {
        http_response_code($code);
        
        $response = [
            'success' => true,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ];
        
        echo json_encode($response, JSON_PRETTY_PRINT);
        exit();
    }
    
    /**
     * Send an error response
     * 
     * @param string $message Error message
     * @param int $code HTTP status code (default 400)
     * @param array $details Additional error details
     */
    public function error($message = 'An error occurred', $code = 400, $details = []) {
        http_response_code($code);
        
        $response = [
            'success' => false,
            'message' => $message,
            'error_code' => $code,
            'timestamp' => time()
        ];
        
        if (!empty($details)) {
            $response['details'] = $details;
        }
        
        echo json_encode($response, JSON_PRETTY_PRINT);
        exit();
    }
    
    /**
     * Send a validation error response
     * 
     * @param array $errors Validation errors
     * @param string $message Error message
     */
    public function validationError($errors, $message = 'Validation failed') {
        $this->error($message, 422, ['validation_errors' => $errors]);
    }
    
    /**
     * Send a not found response
     * 
     * @param string $message Optional message
     */
    public function notFound($message = 'Resource not found') {
        $this->error($message, 404);
    }
    
    /**
     * Send an unauthorized response
     * 
     * @param string $message Optional message
     */
    public function unauthorized($message = 'Unauthorized access') {
        $this->error($message, 401);
    }
    
    /**
     * Send a forbidden response
     * 
     * @param string $message Optional message
     */
    public function forbidden($message = 'Access forbidden') {
        $this->error($message, 403);
    }
}