<?php

require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/permissions.php';

class DashboardAccessService
{
    private $pdo;

    private $catalog = array(
        'general' => array('id' => 'DB-00', 'label' => 'General', 'icon' => 'layout-dashboard'),
        'executive' => array('id' => 'DB-01', 'label' => 'Ejecutivo', 'icon' => 'gauge'),
        'financial' => array('id' => 'DB-02', 'label' => 'Financiero y CORFO', 'icon' => 'landmark'),
        'commercial' => array('id' => 'DB-03', 'label' => 'Comercial', 'icon' => 'chart-no-axes-combined'),
        'sales' => array('id' => 'DB-04', 'label' => 'Ventas', 'icon' => 'briefcase-business'),
        'marketing' => array('id' => 'DB-05', 'label' => 'Marketing', 'icon' => 'megaphone'),
        'production' => array('id' => 'DB-06', 'label' => 'Producción', 'icon' => 'flask-conical'),
    );

    public function __construct()
    {
        $this->pdo = db();
    }

    public function catalog()
    {
        return $this->catalog;
    }

    public function allowedDashboards($user = null)
    {
        $user = $user ?: current_user();
        $role = isset($user['role']) ? (string)$user['role'] : '';
        $userId = isset($user['id']) ? (int)$user['id'] : 0;

        if ($role === 'admin') {
            return array_keys($this->catalog);
        }

        $explicit = $this->getExplicitAccess($userId);
        if (!empty($explicit)) {
            return array_values(array_filter(array_keys($this->catalog), function ($key) use ($explicit) {
                return !empty($explicit[$key]['can_view']);
            }));
        }

        if ($role === 'administracion') {
            return array('general', 'executive', 'financial', 'commercial');
        }
        if ($role === 'operaciones') {
            return array('general', 'production');
        }
        if ($role === 'comercial') {
            $area = strtolower(trim((string)($user['area'] ?? '')));
            if (strpos($area, 'marketing') !== false) {
                return array('general', 'marketing');
            }
            if (strpos($area, 'geren') !== false || strpos($area, 'manager') !== false || strpos($area, 'direc') !== false) {
                return array('general', 'commercial', 'sales', 'marketing');
            }
            return array('general', 'sales');
        }

        return array('general');
    }

    public function canView($dashboardKey, $user = null)
    {
        return in_array($dashboardKey, $this->allowedDashboards($user), true);
    }

    public function requireView($dashboardKey, $user = null)
    {
        if (!$this->canView($dashboardKey, $user)) {
            http_response_code(403);
            die('No tienes permisos para acceder a este dashboard.');
        }
    }

    public function canConfigure($dashboardKey, $user = null)
    {
        $user = $user ?: current_user();
        $role = isset($user['role']) ? (string)$user['role'] : '';
        $userId = isset($user['id']) ? (int)$user['id'] : 0;

        if ($role === 'admin') return true;
        if ($userId <= 0 || !$this->canView($dashboardKey, $user)) return false;

        $explicit = $this->getExplicitAccess($userId);
        return isset($explicit[$dashboardKey]) && !empty($explicit[$dashboardKey]['can_configure']);
    }

    public function requireConfigure($dashboardKey, $user = null)
    {
        if (!$this->canConfigure($dashboardKey, $user)) {
            http_response_code(403);
            die('No tienes permisos para configurar este dashboard.');
        }
    }

    public function canExport($dashboardKey, $user = null)
    {
        $user = $user ?: current_user();
        $role = isset($user['role']) ? (string)$user['role'] : '';
        $userId = isset($user['id']) ? (int)$user['id'] : 0;

        if ($role === 'admin') return true;
        if ($userId <= 0 || !$this->canView($dashboardKey, $user)) return false;

        $explicit = $this->getExplicitAccess($userId);
        return isset($explicit[$dashboardKey]) && !empty($explicit[$dashboardKey]['can_export']);
    }

    public function requireExport($dashboardKey, $user = null)
    {
        if (!$this->canExport($dashboardKey, $user)) {
            http_response_code(403);
            die('No tienes permisos para exportar este dashboard.');
        }
    }

    public function defaultDashboard($user = null)
    {
        $allowed = $this->allowedDashboards($user);
        if (in_array('executive', $allowed, true)) return 'executive';
        if (in_array('sales', $allowed, true)) return 'sales';
        if (in_array('marketing', $allowed, true)) return 'marketing';
        if (in_array('production', $allowed, true)) return 'production';
        return isset($allowed[0]) ? $allowed[0] : 'general';
    }

    private function getExplicitAccess($userId)
    {
        if ($userId <= 0) return array();

        try {
            $stmt = $this->pdo->prepare("SELECT dashboard_key, can_view, can_configure, can_export FROM dashboard_user_access WHERE user_id = ?");
            $stmt->execute(array($userId));
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Throwable $e) {
            return array();
        }

        $access = array();
        foreach ($rows as $row) {
            $key = (string)$row['dashboard_key'];
            $access[$key] = array(
                'can_view' => (int)$row['can_view'] === 1,
                'can_configure' => (int)$row['can_configure'] === 1,
                'can_export' => (int)$row['can_export'] === 1,
            );
        }
        return $access;
    }
}
