<?php
require_once dirname(__DIR__) . '/models/Users.php';
require_once dirname(__DIR__) . '/models/Detail_Pemesanan.php';
require_once dirname(__DIR__) . '/controllers/BaseController.php';

class UserController extends BaseController {
    public function __construct(mysqli $conn) {
        parent::__construct($conn);
    }

    public function index() {
        $this->requireAdmin();
        $userModel = new Users($this->conn);
        $users = $userModel->getAllUsers();
        $this->view('user', ['users' => $users]);
    }

    public function detail($user_id = null) {
        if ($user_id === null && isset($_SESSION['user_id'])) {
            $user_id = $_SESSION['user_id'];
        }

        if ($user_id === null) {
            $this->setErrorMessage("Anda harus login untuk melihat detail pengguna.");
            $this->redirect('login');
            exit();
        }

        if (!isset($_SESSION['user_role']) || ($_SESSION['user_role'] !== 'admin' && ($_SESSION['user_id'] ?? null) != $user_id)) {
            $this->setErrorMessage("Anda tidak memiliki izin untuk mengakses profil ini.");
            $this->redirect('home');
            exit();
        }

        $userModel = new Users($this->conn);
        $detailPemesananModel = new Detail_Pemesanan($this->conn);
        $user = $userModel->getUserById($user_id);
        $pemesanan_list = $detailPemesananModel->getPemesananByUser($user_id);

        if (!$user) {
            $this->setErrorMessage("Pengguna tidak ditemukan.");
            $this->redirect('user');
            exit();
        }

        $this->view('user_detail', ['user' => $user, 'pemesanan_list' => $pemesanan_list]);
    }

    public function create() {
        $this->requireAdmin();
        $this->view('user_form');
    }

    public function store() {
        $this->requireAdmin();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $fullname = $_POST['fullname'] ?? '';
            $jenis_kelamin = $_POST['jenis_kelamin'] ?? '';
            $email = $_POST['email'] ?? '';
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? '';
            $role = $_POST['role'] ?? 'user';
            $no_hp = $_POST['no_hp'] ?? null;
            $foto = null;

            if (empty($fullname) || empty($jenis_kelamin) || empty($email) || empty($username) || empty($password)) {
                $this->setErrorMessage("Semua kolom wajib diisi.");
                $this->redirect('user_create');
                exit();
            }

            $userModel = new Users($this->conn);
            $result = $userModel->addUser($fullname, $jenis_kelamin, $email, $username, $password, $no_hp, $role, $foto);

            if ($result) {
                $this->setSuccessMessage("Pengguna berhasil ditambahkan.");
                $this->redirect('user');
            } else {
                $this->setErrorMessage("Gagal menambahkan pengguna. Username atau Email mungkin sudah terdaftar.");
                $this->redirect('user_create');
            }
            exit();
        }

        $this->redirect('user_create');
    }

    public function edit($user_id) {
        if (!isset($_SESSION['user_role']) || ($_SESSION['user_role'] !== 'admin' && ($_SESSION['user_id'] ?? null) != $user_id)) {
            $this->setErrorMessage("Anda tidak memiliki izin untuk mengedit profil ini.");
            $this->redirect('home');
            exit();
        }

        $userModel = new Users($this->conn);
        $user = $userModel->getUserById($user_id);

        if (!$user) {
            $this->setErrorMessage("Pengguna tidak ditemukan.");
            $this->redirect('user');
            exit();
        }

        $this->view('user_form_update', ['user' => $user]);
    }

    public function update() {
        if (!isset($_SESSION['user_role']) || ($_SESSION['user_role'] !== 'admin' && ($_SESSION['user_id'] ?? null) != ($_POST['id'] ?? null))) {
            $this->setErrorMessage("Anda tidak memiliki izin untuk memperbarui profil ini.");
            $this->redirect('home');
            exit();
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $id = $_POST['id'] ?? null;
            $fullname = $_POST['fullname'] ?? '';
            $jenis_kelamin = $_POST['jenis_kelamin'] ?? '';
            $email = $_POST['email'] ?? '';
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? null;
            $no_hp = $_POST['no_hp'] ?? null;
            $old_foto = $_POST['old_foto'] ?? null;

            // Hanya admin boleh ubah role
            if ($_SESSION['user_role'] === 'admin') {
                $role = $_POST['role'] ?? 'user';
            } else {
                $role = $_SESSION['user_role'];
            }

            $foto = $old_foto;

            if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = dirname(__DIR__) . '/assets/profile/';
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
                $file_name = uniqid() . '_' . basename($_FILES['foto']['name']);
                $target_file = $upload_dir . $file_name;

                if (move_uploaded_file($_FILES['foto']['tmp_name'], $target_file)) {
                    $foto = 'assets/profile/' . $file_name;
                    if ($old_foto && file_exists(dirname(__DIR__) . '/' . $old_foto)) {
                        unlink(dirname(__DIR__) . '/' . $old_foto);
                    }
                } else {
                    $this->setErrorMessage("Gagal mengupload foto profil baru.");
                    $this->redirect('user_edit', ['id' => $id]);
                    exit();
                }
            }

            $userModel = new Users($this->conn);
            $result = $userModel->updateUser($id, $fullname, $jenis_kelamin, $email, $username, $password, $no_hp, $role, $foto);

            if ($result) {
                $this->setSuccessMessage("Profil pengguna berhasil diperbarui.");

                if ($id == ($_SESSION['user_id'] ?? null)) {
                    $_SESSION['username'] = $username;
                    $_SESSION['user_role'] = $role;
                    $_SESSION['fullname'] = $fullname;
                    $_SESSION['foto'] = $foto;
                }

                $this->redirect('user_detail', ['id' => $id]);
            } else {
                $this->setErrorMessage("Gagal memperbarui profil. Username atau Email mungkin sudah terdaftar.");
                $this->redirect('user_edit', ['id' => $id]);
            }
            exit();
        }

        $this->redirect('user');
    }

    public function destroy($user_id) {
        $this->requireAdmin();

        if ($user_id == ($_SESSION['user_id'] ?? null)) {
            $this->setErrorMessage("Anda tidak bisa menghapus akun Anda sendiri.");
            $this->redirect('user');
            exit();
        }

        $userModel = new Users($this->conn);
        $detailPemesananModel = new Detail_Pemesanan($this->conn);

        if ($detailPemesananModel->getPemesananCountByUser($user_id) > 0) {
            $this->setErrorMessage("Tidak bisa menghapus pengguna. Ada pemesanan terkait pengguna ini.");
            $this->redirect('user');
            exit();
        }

        $result = $userModel->deleteUser($user_id);

        if ($result) {
            $this->setSuccessMessage("Pengguna berhasil dihapus.");
        } else {
            $this->setErrorMessage("Gagal menghapus pengguna. Kendala database.");
        }

        $this->redirect('user');
    }
}
