<?php
/**
 * Rencana Kerja Permission System - ACF Eduhub
 * Mengatur akses berdasarkan role A (Admin), M (Manager/Dept Operasional), S (Staff)
 * 
 * FIXED: Removed all references to non-existent 'nama' column
 * Database columns: id, full_name, username, role, department, is_active
 */
class RencanaKerjaPermission {
    private $conn;
    private $userId;
    private $userRole;
    private $userDepartment;
    private $userName;
    
    // Role constants sesuai sistem ACF
    const ROLE_ADMIN = 'A';
    const ROLE_MANAGER = 'M';
    const ROLE_STAFF = 'S';
    
    public function __construct($conn, $userId, $userRole) {
        $this->conn = $conn;
        $this->userId = $userId;
        $this->userRole = strtoupper(trim($userRole));
        
        // ✅ FIXED: Only query existing columns
        $stmt = $conn->prepare("
            SELECT department, full_name, username 
            FROM users 
            WHERE id = ?
        ");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            $this->userDepartment = $row['department'] ?? '';
            // Prioritize full_name, fallback to username
            $this->userName = $row['full_name'] ?: ($row['username'] ?? 'User');
        }
        $stmt->close();
    }
    
    /**
     * Check if user can create tasks
     * - Admin (A): Yes, dapat assign ke siapa saja
     * - Manager (M): Yes, dapat assign ke tim departemennya
     * - Staff (S): Yes, HANYA untuk diri sendiri
     */
    public function canCreate() {
        return in_array($this->userRole, [
            self::ROLE_ADMIN,
            self::ROLE_MANAGER,
            self::ROLE_STAFF
        ]);
    }
    
    /**
     * Check if user can update a specific task
     */
    public function canUpdate($taskId = null) {
        switch ($this->userRole) {
            case self::ROLE_ADMIN:
                return true; // Admin bisa update semua
                
            case self::ROLE_MANAGER:
                // Manager bisa update tugas di departemennya
                if ($taskId) {
                    return $this->isTaskInMyDepartment($taskId);
                }
                return true;
                
            case self::ROLE_STAFF:
                // Staff bisa update tugas yang dia buat atau yang ditugaskan ke dia
                if ($taskId) {
                    return $this->isMyTask($taskId);
                }
                return true;
                
            default:
                return false;
        }
    }
    
    /**
     * Check if user can delete a specific task
     */
    public function canDelete($taskId = null) {
        switch ($this->userRole) {
            case self::ROLE_ADMIN:
                return true; // Admin bisa delete semua
                
            case self::ROLE_MANAGER:
                // Manager bisa delete tugas di departemennya
                if ($taskId) {
                    return $this->isTaskInMyDepartment($taskId);
                }
                return true;
                
            case self::ROLE_STAFF:
                // Staff bisa delete tugas yang dia buat
                if ($taskId) {
                    return $this->isTaskCreatedByMe($taskId);
                }
                return false;
                
            default:
                return false;
        }
    }
    
    /**
     * Check if user can view all tasks
     */
    public function canViewAll() {
        return in_array($this->userRole, [
            self::ROLE_ADMIN,
            self::ROLE_MANAGER
        ]);
    }
    
    /**
     * Get SQL filter for viewing tasks based on user role
     * ⚠️ WARNING: This returns a SQL fragment for backward compatibility
     * New code should use native queries in view files instead
     */
    public function getViewFilter() {
        switch ($this->userRole) {
            case self::ROLE_ADMIN:
                // Admin bisa lihat semua
                return "";
                
            case self::ROLE_MANAGER:
                // Manager lihat semua tugas di departemennya
                if ($this->userDepartment) {
                    $dept = $this->conn->real_escape_string($this->userDepartment);
                    return " AND (rk.department = '{$dept}' OR assignee.department = '{$dept}')";
                }
                return "";
                
            case self::ROLE_STAFF:
                // Staff hanya lihat tugas yang ditugaskan ke dia atau yang dia buat
                return " AND (rk.assigned_to = {$this->userId} OR rk.created_by = {$this->userId})";
                
            default:
                return " AND 1=0"; // No access
        }
    }
    
    /**
     * Get list of users that current user can assign tasks to
     * ✅ FIXED: Removed 'nama' column from all queries
     */
    public function getAssignableUsers() {
        $users = [];
        
        switch ($this->userRole) {
            case self::ROLE_ADMIN:
                // Admin bisa assign ke semua user
                // ✅ FIXED: Only query existing columns
                $query = "
                    SELECT id, full_name, username, role, department 
                    FROM users 
                    WHERE is_active = 1 
                    ORDER BY department, full_name
                ";
                break;
                
            case self::ROLE_MANAGER:
                // Manager hanya bisa assign ke staff di departemennya
                if ($this->userDepartment) {
                    $dept = $this->conn->real_escape_string($this->userDepartment);
                    // ✅ FIXED: Only query existing columns
                    $query = "
                        SELECT id, full_name, username, role, department 
                        FROM users 
                        WHERE is_active = 1 
                        AND department = '{$dept}'
                        AND role IN ('M', 'S')
                        ORDER BY full_name
                    ";
                } else {
                    return [];
                }
                break;
                
            case self::ROLE_STAFF:
                // Staff hanya bisa assign ke dirinya sendiri
                // ✅ FIXED: Only query existing columns
                $query = "
                    SELECT id, full_name, username, role, department 
                    FROM users 
                    WHERE id = {$this->userId}
                ";
                break;
                
            default:
                return [];
        }
        
        $result = $this->conn->query($query);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                // ✅ FIXED: Normalize user name without 'nama'
                $row['display_name'] = $row['full_name'] ?: ($row['username'] ?? 'User');
                $users[] = $row;
            }
        }
        
        return $users;
    }
    
    /**
     * Get permission summary
     */
    public function getPermissionSummary() {
        $roleNames = [
            'A' => 'Administrator',
            'M' => 'Dept Operasional',
            'S' => 'Staff'
        ];
        
        return [
            'can_create' => $this->canCreate(),
            'can_update' => $this->canUpdate(),
            'can_delete' => $this->canDelete(),
            'can_view_all' => $this->canViewAll(),
            'role' => $this->userRole,
            'role_name' => $roleNames[$this->userRole] ?? 'Unknown',
            'department' => $this->userDepartment,
            'user_name' => $this->userName,
            'user_id' => $this->userId
        ];
    }
    
    /**
     * Check if task is in user's department
     */
    private function isTaskInMyDepartment($taskId) {
        $stmt = $this->conn->prepare("
            SELECT COUNT(*) as count 
            FROM rencana_kerja rk
            LEFT JOIN users u ON rk.assigned_to = u.id
            WHERE rk.id = ? 
            AND (rk.department = ? OR u.department = ?)
        ");
        $stmt->bind_param("iss", $taskId, $this->userDepartment, $this->userDepartment);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        return $result['count'] > 0;
    }
    
    /**
     * Check if task belongs to current user (assigned or created)
     */
    private function isMyTask($taskId) {
        $stmt = $this->conn->prepare("
            SELECT COUNT(*) as count 
            FROM rencana_kerja 
            WHERE id = ? 
            AND (assigned_to = ? OR created_by = ?)
        ");
        $stmt->bind_param("iii", $taskId, $this->userId, $this->userId);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        return $result['count'] > 0;
    }
    
    /**
     * Check if task was created by current user
     */
    private function isTaskCreatedByMe($taskId) {
        $stmt = $this->conn->prepare("
            SELECT COUNT(*) as count 
            FROM rencana_kerja 
            WHERE id = ? 
            AND created_by = ?
        ");
        $stmt->bind_param("ii", $taskId, $this->userId);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        return $result['count'] > 0;
    }
    
    /**
     * Validate task creation
     */
    public function validateTaskCreation($assignedTo, $department = null) {
        if (!$this->canCreate()) {
            return ['valid' => false, 'message' => 'Anda tidak memiliki akses untuk membuat tugas'];
        }
        
        // Staff hanya bisa assign ke diri sendiri
        if ($this->userRole === self::ROLE_STAFF && $assignedTo != $this->userId) {
            return ['valid' => false, 'message' => 'Staff hanya dapat membuat tugas untuk diri sendiri'];
        }
        
        // Manager hanya bisa assign ke staff di departemennya
        if ($this->userRole === self::ROLE_MANAGER) {
            $stmt = $this->conn->prepare("
                SELECT department 
                FROM users 
                WHERE id = ?
            ");
            $stmt->bind_param("i", $assignedTo);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if ($result && $result['department'] !== $this->userDepartment) {
                return ['valid' => false, 'message' => 'Anda hanya dapat menugaskan ke anggota departemen Anda'];
            }
        }
        
        return ['valid' => true];
    }
    
    /**
     * Get departments that user can access
     */
    public function getAccessibleDepartments() {
        switch ($this->userRole) {
            case self::ROLE_ADMIN:
                // Get all departments
                $query = "
                    SELECT DISTINCT department 
                    FROM users 
                    WHERE department IS NOT NULL 
                    AND department != '' 
                    ORDER BY department
                ";
                break;
                
            case self::ROLE_MANAGER:
            case self::ROLE_STAFF:
                // Only own department
                return $this->userDepartment ? [$this->userDepartment] : [];
                
            default:
                return [];
        }
        
        $departments = [];
        $result = $this->conn->query($query);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $departments[] = $row['department'];
            }
        }
        
        return $departments;
    }
}