<?php
/**
 * Base Controller Class
 * All controllers extend this class
 * 
 * @package RashwansBarber
 * @version 1.0
 */

class Controller {
    
    protected $db;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Load a model
     * 
     * @param string $model Model name
     * @return object Model instance
     */
    protected function model($model) {
        $modelPath = __DIR__ . '/../models/' . $model . '.php';
        
        if (file_exists($modelPath)) {
            require_once $modelPath;
            return new $model();
        } else {
            die("Model {$model} not found");
        }
    }
    
    /**
     * Load a view
     * 
     * @param string $view View file name
     * @param array $data Data to pass to view
     */
    protected function view($view, $data = []) {
        // Extract data array to variables
        extract($data);
        
        $viewPath = __DIR__ . '/../views/' . $view . '.php';
        
        if (file_exists($viewPath)) {
            require_once $viewPath;
        } else {
            die("View {$view} not found");
        }
    }
    
    /**
     * Redirect to another page
     * 
     * @param string $url URL to redirect to
     */
    protected function redirect($url) {
        $baseUrl = $this->getBaseUrl();
        header("Location: {$baseUrl}/{$url}");
        exit;
    }
    
    /**
     * Get base URL
     * 
     * @return string
     */
    protected function getBaseUrl() {
        return '';
    }
    
    /**
     * Check if user is logged in
     * 
     * @return bool
     */
    protected function isLoggedIn() {
        return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
    }
    
    /**
     * Require login - redirect to login if not logged in
     */
    protected function requireLogin() {
        if (!$this->isLoggedIn()) {
            $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
            $this->redirect('login');
        }
    }
    
    /**
     * Check if user has specific role
     * 
     * @param string|array $roles Role name(s) to check
     * @return bool
     */
    protected function hasRole($roles) {
        if (!$this->isLoggedIn()) {
            return false;
        }
        
        $userRole = $_SESSION['role_name'] ?? '';
        
        if (is_array($roles)) {
            return in_array($userRole, $roles);
        }
        
        return $userRole === $roles;
    }
    
    /**
     * Require specific role - redirect if user doesn't have permission
     * 
     * @param string|array $roles Required role(s)
     */
    protected function requireRole($roles) {
        $this->requireLogin();
        
        if (!$this->hasRole($roles)) {
            $this->redirect('dashboard?error=access_denied');
        }
    }
    
    /**
     * Get current user data
     * 
     * @return array|null
     */
    protected function getCurrentUser() {
        if (!$this->isLoggedIn()) {
            return null;
        }
        
        return [
            'user_id' => $_SESSION['user_id'] ?? null,
            'username' => $_SESSION['username'] ?? null,
            'full_name' => $_SESSION['full_name'] ?? null,
            'role_id' => $_SESSION['role_id'] ?? null,
            'role_name' => $_SESSION['role_name'] ?? null,
            'location_id' => $_SESSION['location_id'] ?? null,
            'location_name' => $_SESSION['location_name'] ?? null
        ];
    }
    
    /**
     * Return JSON response
     * 
     * @param mixed $data Data to return
     * @param int $statusCode HTTP status code
     */
    protected function json($data, $statusCode = 200) {
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
    
    /**
     * Validate CSRF token
     * 
     * @param string $token Token from form
     * @return bool
     */
    protected function validateCSRF($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
    
    /**
     * Generate CSRF token
     * 
     * @return string
     */
    protected function generateCSRF() {
        if (!isset($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }
    /**
    * Alias for generateCSRF() - for compatibility
    */
    protected function generateCsrfToken() {
        return $this->generateCSRF();
    }  
    /**
     * Sanitize input
     * 
     * @param mixed $data Data to sanitize
     * @return mixed
     */
    protected function sanitize($data) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $data[$key] = $this->sanitize($value);
            }
            return $data;
        }
        
        return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
    }
    
    /**
     * Flash message - set
     * 
     * @param string $message Message text
     * @param string $type success, error, warning, info
     */
    protected function setFlash($message, $type = 'info') {
        $_SESSION['flash_message'] = $message;
        $_SESSION['flash_type'] = $type;
    }
    
    /**
     * Flash message - get and clear
     * 
     * @return array|null
     */
    protected function getFlash() {
        if (isset($_SESSION['flash_message'])) {
            $flash = [
                'message' => $_SESSION['flash_message'],
                'type' => $_SESSION['flash_type'] ?? 'info'
            ];
            
            unset($_SESSION['flash_message']);
            unset($_SESSION['flash_type']);
            
            return $flash;
        }
        return null;
    }
    
    /**
     * Log audit action
     * 
     * @param string $action Action performed
     * @param string $tableName Table affected
     * @param int $recordId Record ID
     * @param array $oldValues Old values
     * @param array $newValues New values
     */
    protected function logAudit($action, $tableName = null, $recordId = null, $oldValues = null, $newValues = null) {
        try {
            $sql = "INSERT INTO audit_logs (user_id, action, table_name, record_id, old_values, new_values, ip_address, user_agent) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            
            $this->db->query($sql, [
                $_SESSION['user_id'] ?? null,
                $action,
                $tableName,
                $recordId,
                $oldValues ? json_encode($oldValues) : null,
                $newValues ? json_encode($newValues) : null,
                $_SERVER['REMOTE_ADDR'] ?? null,
                $_SERVER['HTTP_USER_AGENT'] ?? null
            ]);
        } catch (Exception $e) {
            error_log("Audit log failed: " . $e->getMessage());
        }
    }
    
    /**
     * Generate a "coming soon" placeholder page
     * 
     * @param string $pageName Page name to display
     * @param string $icon Font Awesome icon name
     * @return string HTML content
     */
    protected function comingSoonPage($pageName, $icon = 'tools') {
        return '<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>' . $pageName . ' - ' . config('app_name') . '</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <style>
        body { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        }
        .coming-soon-card {
            background: white;
            border-radius: 20px;
            padding: 50px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            text-align: center;
            max-width: 500px;
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .icon-circle {
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 30px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }
    </style>
</head>
<body>
    <div class="coming-soon-card">
        <div class="icon-circle">
            <i class="fas fa-' . $icon . ' fa-3x text-white"></i>
        </div>
        <h1 class="mb-3">' . $pageName . '</h1>
        <p class="lead text-muted mb-4">This feature is under development and will be available soon!</p>
        <a href="' . url('dashboard') . '" class="btn btn-primary btn-lg">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>
</body>
</html>';
    }
}
?>
