<?php

require_once '../app/Models/User.php';
require_once '../app/Models/UserType.php';

class UserController
{
    private $userModel;
    private $userTypeModel;
    
    public function __construct()
    {
        $this->userModel = new User();
        $this->userTypeModel = new UserType();
        $this->checkAuth();
    }
    
    private function checkAuth()
    {
        if (!isset($_SESSION['user_id'])) {
            header('Location: /samanta_crm/login');
            exit;
        }
    }
    
    public function dashboard()
    {
        require_once '../bootstrap/db.php';
        global $pdo;
        
        // Get recent users (limit 5) and total user count
        $recent = $this->userModel->searchPaginated('', 'all', 1, 5);
        
        // Get orders statistics (with error handling)
        try {
            $totalOrdersStmt = $pdo->query("SELECT COUNT(*) as total FROM orders");
            $totalOrders = $totalOrdersStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
            
            $pendingOrdersStmt = $pdo->query("SELECT COUNT(*) as total FROM orders WHERE status = 'pending'");
            $pendingOrders = $pendingOrdersStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
        } catch (Exception $e) {
            $totalOrders = 0;
            $pendingOrders = 0;
        }
        
        // Get ingredients with low or critical stock levels
        try {
            $lowStockStmt = $pdo->query("
                SELECT 
                    i.id,
                    i.name, 
                    i.unit, 
                    COALESCE(SUM(s.change_qty), 0) as total_stock,
                    i.low_stock,
                    i.critical_low_stock,
                    i.high_stock,
                    i.critical_high_stock,
                    CASE 
                        WHEN i.critical_low_stock IS NOT NULL AND COALESCE(SUM(s.change_qty), 0) <= i.critical_low_stock THEN 'critical_low'
                        WHEN i.low_stock IS NOT NULL AND COALESCE(SUM(s.change_qty), 0) <= i.low_stock THEN 'low'
                        WHEN i.critical_high_stock IS NOT NULL AND COALESCE(SUM(s.change_qty), 0) >= i.critical_high_stock THEN 'critical_high'
                        WHEN i.high_stock IS NOT NULL AND COALESCE(SUM(s.change_qty), 0) >= i.high_stock THEN 'high'
                        ELSE 'normal'
                    END as stock_status
                FROM ingredients i 
                LEFT JOIN ingredient_storage s ON i.id = s.ingredient_id 
                GROUP BY i.id, i.name, i.unit, i.low_stock, i.critical_low_stock, i.high_stock, i.critical_high_stock
            ");
            $allIngredients = $lowStockStmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Filter only alerts
            $lowStockIngredients = array_filter($allIngredients, function($ing) {
                return in_array($ing['stock_status'], ['critical_low', 'low', 'critical_high', 'high']);
            });
            
            // Re-sort after filtering
            usort($lowStockIngredients, function($a, $b) {
                $priority = ['critical_low' => 1, 'critical_high' => 2, 'low' => 3, 'high' => 4];
                $aPriority = $priority[$a['stock_status']] ?? 5;
                $bPriority = $priority[$b['stock_status']] ?? 5;
                if ($aPriority !== $bPriority) {
                    return $aPriority - $bPriority;
                }
                return strcmp($a['name'], $b['name']);
            });
        } catch (Exception $e) {
            error_log("Dashboard stock alerts error: " . $e->getMessage());
            $lowStockIngredients = [];
        }
        
        $data = [
            'users' => $recent['data'] ?? [],
            'totalUsers' => $this->userModel->countAll(),
            'totalOrders' => $totalOrders,
            'pendingOrders' => $pendingOrders,
            'lowStockIngredients' => $lowStockIngredients
        ];
        
        $this->view('dashboard', $data);
    }
    
    public function index()
    {
        $q = trim($_GET['q'] ?? '');
        $status = $_GET['status'] ?? 'all';
        $page = max(1, (int)($_GET['page'] ?? 1));
        $perPage = 10;
        $result = $this->userModel->searchPaginated($q, $status, $page, $perPage);
        $this->view('users/index', [
            'users' => $result['data'],
            'pagination' => $result,
            'filter_q' => $q,
            'filter_status' => $status
        ]);
    }
    
    public function create()
    {
        $userTypes = $this->userTypeModel->getAll(true); // Only active user types
        $this->view('users/create', ['userTypes' => $userTypes]);
    }
    
    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/users/create');
            exit;
        }
        
        $data = [
            'name' => $_POST['name'] ?? '',
            'email' => $_POST['email'] ?? '',
            'password' => $_POST['password'] ?? '',
            'role' => $_POST['role'] ?? 'user',
            'user_type_id' => !empty($_POST['user_type_id']) ? $_POST['user_type_id'] : null
        ];
        
        // Validation
        if (empty($data['name']) || empty($data['email']) || empty($data['password'])) {
            $_SESSION['error'] = 'All fields are required';
            header('Location: /samanta_crm/users/create');
            exit;
        }
        
        // Check if email already exists
        if ($this->userModel->findByEmail($data['email'])) {
            $_SESSION['error'] = 'Email already exists';
            header('Location: /samanta_crm/users/create');
            exit;
        }
        
        if ($this->userModel->create($data)) {
            $_SESSION['success'] = 'User created successfully';
        } else {
            $_SESSION['error'] = 'Failed to create user';
        }
        
        header('Location: /samanta_crm/users');
        exit;
    }
    
    public function edit($id)
    {
        $user = $this->userModel->findById($id);
        
        if (!$user) {
            $_SESSION['error'] = 'User not found';
            header('Location: /samanta_crm/users');
            exit;
        }
        
        $userTypes = $this->userTypeModel->getAll(true); // Only active user types
        $this->view('users/edit', [
            'user' => $user,
            'userTypes' => $userTypes
        ]);
    }
    
    public function update($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/users');
            exit;
        }
        
        $data = [
            'name' => $_POST['name'] ?? '',
            'email' => $_POST['email'] ?? '',
            'role' => $_POST['role'] ?? 'user',
            'user_type_id' => !empty($_POST['user_type_id']) ? $_POST['user_type_id'] : null,
            'status' => $_POST['status'] ?? 'active'
        ];
        
        if (empty($data['name']) || empty($data['email'])) {
            $_SESSION['error'] = 'Name and email are required';
            header('Location: /samanta_crm/users/' . $id . '/edit');
            exit;
        }
        
        // Handle password change
        $newPassword = trim($_POST['new_password'] ?? '');
        $confirmPassword = trim($_POST['confirm_password'] ?? '');
        
        if (!empty($newPassword)) {
            if ($newPassword !== $confirmPassword) {
                $_SESSION['error'] = 'New passwords do not match';
                header('Location: /samanta_crm/users/' . $id . '/edit');
                exit;
            }
            
            if (strlen($newPassword) < 6) {
                $_SESSION['error'] = 'Password must be at least 6 characters';
                header('Location: /samanta_crm/users/' . $id . '/edit');
                exit;
            }
            
            // Update password separately
            if (!$this->userModel->updatePassword($id, $newPassword)) {
                $_SESSION['error'] = 'Failed to update password';
                header('Location: /samanta_crm/users/' . $id . '/edit');
                exit;
            }
        }
        
        if ($this->userModel->update($id, $data)) {
            $_SESSION['success'] = $newPassword ? 'User and password updated successfully' : 'User updated successfully';
        } else {
            $_SESSION['error'] = 'Failed to update user';
        }
        
        header('Location: /samanta_crm/users');
        exit;
    }
    
    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /samanta_crm/users');
            exit;
        }
        
        if ($this->userModel->delete($id)) {
            $_SESSION['success'] = 'User archived (soft deleted)';
        } else {
            $_SESSION['error'] = 'Failed to delete user';
        }
        
        header('Location: /samanta_crm/users');
        exit;
    }

    public function restore($id) {
        if ($this->userModel->restore($id)) {
            $_SESSION['success'] = 'User restored';
        } else {
            $_SESSION['error'] = 'Failed to restore user';
        }
        header('Location: /samanta_crm/users');
        exit;
    }
    
    private function view($view, $data = [])
    {
        extract($data);
        require_once "../app/Views/{$view}.php";
    }
}
