<?php
// includes/auth.php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once 'database.php';
require_once 'functions.php';

class Auth {
    private $db;
    
    public function __construct() {
        $this->db = dbConnect();
    }
    
    // Register user (hanya untuk donatur)
    public function register($data) {
        // Sanitize data
        $username = sanitize($data['username']);
        $password = password_hash($data['password'], PASSWORD_DEFAULT);
        $nama_lengkap = sanitize($data['nama_lengkap']);
        $email = sanitize($data['email']);
        $no_telp = isset($data['no_telp']) ? sanitize($data['no_telp']) : null;
        $alamat = isset($data['alamat']) ? sanitize($data['alamat']) : null;
        $role = 'donatur'; // Default role
        
        // Cek apakah username sudah terdaftar
        $this->db->query("SELECT * FROM users WHERE username = :username");
        $this->db->bind(':username', $username);
        $user = $this->db->single();
        
        if($user) {
            return [
                'status' => false,
                'message' => 'Username sudah terdaftar'
            ];
        }
        
        // Cek apakah email sudah terdaftar
        $this->db->query("SELECT * FROM users WHERE email = :email");
        $this->db->bind(':email', $email);
        $user = $this->db->single();
        
        if($user) {
            return [
                'status' => false,
                'message' => 'Email sudah terdaftar'
            ];
        }
        
        // Insert user
        $this->db->query("INSERT INTO users (username, password, nama_lengkap, email, no_telp, alamat, role) VALUES (:username, :password, :nama_lengkap, :email, :no_telp, :alamat, :role)");
        $this->db->bind(':username', $username);
        $this->db->bind(':password', $password);
        $this->db->bind(':nama_lengkap', $nama_lengkap);
        $this->db->bind(':email', $email);
        $this->db->bind(':no_telp', $no_telp);
        $this->db->bind(':alamat', $alamat);
        $this->db->bind(':role', $role);
        
        if($this->db->execute()) {
            // Log aktivitas
            $this->logActivity($this->db->lastInsertId(), 'Registrasi user baru', 'user', $this->db->lastInsertId(), 'User baru mendaftar dengan username: ' . $username);
            
            return [
                'status' => true,
                'message' => 'Registrasi berhasil',
                'user_id' => $this->db->lastInsertId()
            ];
        } else {
            return [
                'status' => false,
                'message' => 'Registrasi gagal'
            ];
        }
    }
    
    // Login user
    public function login($username, $password) {
        // Sanitize data
        $username = sanitize($username);
        
        // Cek username
        $this->db->query("SELECT * FROM users WHERE username = :username");
        $this->db->bind(':username', $username);
        $user = $this->db->single();
        
        if(!$user) {
            return [
                'status' => false,
                'message' => 'Username tidak ditemukan'
            ];
        }
        
        // Verifikasi password
        if(password_verify($password, $user->password)) {
            // Set session
            $_SESSION['user_id'] = $user->id;
            $_SESSION['username'] = $user->username;
            $_SESSION['nama_lengkap'] = $user->nama_lengkap;
            $_SESSION['email'] = $user->email;
            $_SESSION['role'] = $user->role;
            
            // Log aktivitas
            $this->logActivity($user->id, 'Login', 'user', $user->id, 'User login ke sistem');
            
            return [
                'status' => true,
                'message' => 'Login berhasil',
                'user' => $user
            ];
        } else {
            return [
                'status' => false,
                'message' => 'Password salah'
            ];
        }
    }
    
    // Logout user
    public function logout() {
        // Log aktivitas sebelum session dihapus
        if(isset($_SESSION['user_id'])) {
            $this->logActivity($_SESSION['user_id'], 'Logout', 'user', $_SESSION['user_id'], 'User logout dari sistem');
        }
        
        // Hapus semua session
        session_unset();
        session_destroy();
        
        return [
            'status' => true,
            'message' => 'Logout berhasil'
        ];
    }
    
    // Cek user sudah login
    public function isLoggedIn() {
        return isset($_SESSION['user_id']);
    }
    
    // Cek role user
    public function hasRole($role) {
        if (!isset($_SESSION['role'])) {
            return false;
        }
        
        if (is_array($role)) {
            return in_array($_SESSION['role'], $role);
        } else {
            return $_SESSION['role'] == $role;
        }
    }
    
    // Get user by id
    public function getUserById($id) {
        $this->db->query("SELECT * FROM users WHERE id = :id");
        $this->db->bind(':id', $id);
        return $this->db->single();
    }
    
    // Update profile
    public function updateProfile($data) {
        // Sanitize data
        $id = $_SESSION['user_id'];
        $nama_lengkap = sanitize($data['nama_lengkap']);
        $email = sanitize($data['email']);
        $no_telp = isset($data['no_telp']) ? sanitize($data['no_telp']) : null;
        $alamat = isset($data['alamat']) ? sanitize($data['alamat']) : null;
        
        // Update user
        $this->db->query("UPDATE users SET nama_lengkap = :nama_lengkap, email = :email, no_telp = :no_telp, alamat = :alamat WHERE id = :id");
        $this->db->bind(':nama_lengkap', $nama_lengkap);
        $this->db->bind(':email', $email);
        $this->db->bind(':no_telp', $no_telp);
        $this->db->bind(':alamat', $alamat);
        $this->db->bind(':id', $id);
        
        if($this->db->execute()) {
            // Update session
            $_SESSION['nama_lengkap'] = $nama_lengkap;
            $_SESSION['email'] = $email;
            
            // Log aktivitas
            $this->logActivity($id, 'Update profil', 'user', $id, 'User memperbarui profil');
            
            return [
                'status' => true,
                'message' => 'Profile berhasil diupdate'
            ];
        } else {
            return [
                'status' => false,
                'message' => 'Profile gagal diupdate'
            ];
        }
    }
    
    // Change password
    public function changePassword($data) {
        // Sanitize data
        $id = $_SESSION['user_id'];
        $old_password = $data['old_password'];
        $new_password = $data['new_password'];
        $confirm_password = $data['confirm_password'];
        
        // Cek password lama
        $this->db->query("SELECT * FROM users WHERE id = :id");
        $this->db->bind(':id', $id);
        $user = $this->db->single();
        
        if(!password_verify($old_password, $user->password)) {
            return [
                'status' => false,
                'message' => 'Password lama salah'
            ];
        }
        
        // Cek konfirmasi password
        if($new_password != $confirm_password) {
            return [
                'status' => false,
                'message' => 'Konfirmasi password tidak sesuai'
            ];
        }
        
        // Update password
        $password = password_hash($new_password, PASSWORD_DEFAULT);
        $this->db->query("UPDATE users SET password = :password WHERE id = :id");
        $this->db->bind(':password', $password);
        $this->db->bind(':id', $id);
        
        if($this->db->execute()) {
            // Log aktivitas
            $this->logActivity($id, 'Ganti password', 'user', $id, 'User mengganti password');
            
            return [
                'status' => true,
                'message' => 'Password berhasil diubah'
            ];
        } else {
            return [
                'status' => false,
                'message' => 'Password gagal diubah'
            ];
        }
    }
    
    // Redirect ke halaman dashboard sesuai role
    public function redirectToDashboard() {
        if (!$this->isLoggedIn()) {
            redirect(SITE_URL . '/auth/login.php');
            exit;
        }
        
        switch ($_SESSION['role']) {
            case 'admin':
                redirect(SITE_URL . '/admin/dashboard.php');
                break;
            case 'ketua':
                redirect(SITE_URL . '/ketua/dashboard.php');
                break;
            case 'bendahara':
                redirect(SITE_URL . '/bendahara/dashboard.php');
                break;
            case 'sekretaris':
                redirect(SITE_URL . '/sekretaris/dashboard.php');
                break;
            case 'pengawas':
                redirect(SITE_URL . '/pengawas/dashboard.php');
                break;
            case 'donatur':
                redirect(SITE_URL . '/user/dashboard.php');
                break;
            default:
                redirect(SITE_URL);
                break;
        }
        exit;
    }
    
    // Log aktivitas

// Modifikasi fungsi logActivity pada auth.php

// Log aktivitas
public function logActivity($user_id, $activity, $entity_type, $entity_id = null, $description = null) {
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? null;
    
    // Periksa apakah tabel logs sudah ada tanpa mencoba membuatnya
    try {
        $this->db->query("INSERT INTO logs (user_id, activity, entity_type, entity_id, description, ip_address) 
                         VALUES (:user_id, :activity, :entity_type, :entity_id, :description, :ip_address)");
        $this->db->bind(':user_id', $user_id);
        $this->db->bind(':activity', $activity);
        $this->db->bind(':entity_type', $entity_type);
        $this->db->bind(':entity_id', $entity_id);
        $this->db->bind(':description', $description);
        $this->db->bind(':ip_address', $ip_address);
        
        return $this->db->execute();
    } catch (PDOException $e) {
        // Jika tabel belum ada, coba buat tabel
        if (strpos($e->getMessage(), "Table 'logs' doesn't exist") !== false) {
            $this->db->query("CREATE TABLE logs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                activity VARCHAR(255) NOT NULL,
                entity_type ENUM('kampanye', 'donasi', 'user', 'berita', 'system') NOT NULL,
                entity_id INT NULL,
                description TEXT NULL,
                ip_address VARCHAR(45) NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");
            
            if ($this->db->execute()) {
                // Setelah tabel dibuat, coba lagi memasukkan log
                $this->db->query("INSERT INTO logs (user_id, activity, entity_type, entity_id, description, ip_address) 
                                VALUES (:user_id, :activity, :entity_type, :entity_id, :description, :ip_address)");
                $this->db->bind(':user_id', $user_id);
                $this->db->bind(':activity', $activity);
                $this->db->bind(':entity_type', $entity_type);
                $this->db->bind(':entity_id', $entity_id);
                $this->db->bind(':description', $description);
                $this->db->bind(':ip_address', $ip_address);
                
                return $this->db->execute();
            }
        }
        
        // Jika error lain, abaikan saja
        return false;
    }
}
    
    // Create notification
    public function createNotification($user_id, $title, $message, $link = null) {
        // Periksa apakah tabel notifications ada
        $this->db->query("SHOW TABLES LIKE 'notifications'");
        $tableExists = $this->db->rowCount() > 0;
        
        // Jika tabel belum ada, buat dulu
        if (!$tableExists) {
            $this->db->query("CREATE TABLE notifications (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NOT NULL,
                title VARCHAR(255) NOT NULL,
                message TEXT NOT NULL,
                is_read BOOLEAN DEFAULT FALSE,
                link VARCHAR(255) NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");
            $this->db->execute();
        }
        
        $this->db->query("INSERT INTO notifications (user_id, title, message, link) 
                         VALUES (:user_id, :title, :message, :link)");
        $this->db->bind(':user_id', $user_id);
        $this->db->bind(':title', $title);
        $this->db->bind(':message', $message);
        $this->db->bind(':link', $link);
        
        return $this->db->execute();
    }
    
    // Get unread notifications
    public function getUnreadNotifications($user_id) {
        // Periksa apakah tabel notifications ada
        $this->db->query("SHOW TABLES LIKE 'notifications'");
        $tableExists = $this->db->rowCount() > 0;
        
        if (!$tableExists) {
            return [];
        }
        
        $this->db->query("SELECT * FROM notifications WHERE user_id = :user_id AND is_read = 0 ORDER BY created_at DESC");
        $this->db->bind(':user_id', $user_id);
        return $this->db->resultSet();
    }
    
    // Mark notification as read
    public function markNotificationAsRead($notification_id) {
        $this->db->query("UPDATE notifications SET is_read = 1 WHERE id = :id");
        $this->db->bind(':id', $notification_id);
        return $this->db->execute();
    }
    
    // Register staff (admin, ketua, bendahara, sekretaris, pengawas)
    public function registerStaff($data) {
        // Sanitize data
        $username = sanitize($data['username']);
        $password = password_hash($data['password'], PASSWORD_DEFAULT);
        $nama_lengkap = sanitize($data['nama_lengkap']);
        $email = sanitize($data['email']);
        $no_telp = isset($data['no_telp']) ? sanitize($data['no_telp']) : null;
        $alamat = isset($data['alamat']) ? sanitize($data['alamat']) : null;
        $role = sanitize($data['role']);
        
        // Validasi role
        $allowed_roles = ['admin', 'ketua', 'bendahara', 'sekretaris', 'pengawas'];
        if (!in_array($role, $allowed_roles)) {
            return [
                'status' => false,
                'message' => 'Role tidak valid'
            ];
        }
        
        // Cek apakah username sudah terdaftar
        $this->db->query("SELECT * FROM users WHERE username = :username");
        $this->db->bind(':username', $username);
        $user = $this->db->single();
        
        if($user) {
            return [
                'status' => false,
                'message' => 'Username sudah terdaftar'
            ];
        }
        
        // Cek apakah email sudah terdaftar
        $this->db->query("SELECT * FROM users WHERE email = :email");
        $this->db->bind(':email', $email);
        $user = $this->db->single();
        
        if($user) {
            return [
                'status' => false,
                'message' => 'Email sudah terdaftar'
            ];
        }
        
        // Insert user
        $this->db->query("INSERT INTO users (username, password, nama_lengkap, email, no_telp, alamat, role) VALUES (:username, :password, :nama_lengkap, :email, :no_telp, :alamat, :role)");
        $this->db->bind(':username', $username);
        $this->db->bind(':password', $password);
        $this->db->bind(':nama_lengkap', $nama_lengkap);
        $this->db->bind(':email', $email);
        $this->db->bind(':no_telp', $no_telp);
        $this->db->bind(':alamat', $alamat);
        $this->db->bind(':role', $role);
        
        if($this->db->execute()) {
            // Log aktivitas
            $this->logActivity($_SESSION['user_id'] ?? $this->db->lastInsertId(), 'Registrasi staff baru', 'user', $this->db->lastInsertId(), 'Staff baru didaftarkan dengan username: ' . $username . ', role: ' . $role);
            
            return [
                'status' => true,
                'message' => 'Registrasi staff berhasil',
                'user_id' => $this->db->lastInsertId()
            ];
        } else {
            return [
                'status' => false,
                'message' => 'Registrasi staff gagal'
            ];
        }
    }
}