<?php
namespace App\Controllers;

use Core\Controller;
use App\Helpers\Helper;

class UserController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin']);
    }

    public function index(): void
    {
        $users = $this->db->fetchAll("SELECT u.*, r.name AS role_name, r.display_name AS role_display FROM users u JOIN roles r ON r.id=u.role_id ORDER BY u.created_at DESC");
        $roles = $this->db->fetchAll("SELECT * FROM roles ORDER BY id");
        $this->adminView('users.index', compact('users','roles') + ['title'=>'System Users']);
    }

    public function store(): void
    {
        $this->verifyCsrf();
        $email = filter_var($this->input('email',''), FILTER_SANITIZE_EMAIL);
        if ($this->db->fetch("SELECT id FROM users WHERE email=?", [$email])) {
            Helper::setFlash('danger','Email already exists.'); $this->back(); return;
        }
        $data = [
            'role_id'    => (int)$this->input('role_id',6),
            'first_name' => Helper::sanitize($this->input('first_name','')),
            'last_name'  => Helper::sanitize($this->input('last_name','')),
            'email'      => $email,
            'phone'      => Helper::sanitize($this->input('phone','')),
            'password'   => password_hash($this->input('password','password123'), PASSWORD_BCRYPT, ['cost'=>12]),
            'status'     => 'active',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        $this->db->insert('users', $data);
        Helper::setFlash('success','User created successfully.');
        $this->redirect(APP_URL.'/admin/users');
    }

    public function edit(string $id): void
    {
        $user  = $this->db->fetch("SELECT * FROM users WHERE id=?", [$id]);
        if (!$user) { $this->abort(404); return; }
        $roles = $this->db->fetchAll("SELECT * FROM roles ORDER BY id");
        $this->adminView('users.edit', compact('user','roles') + ['title'=>'Edit User']);
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();

        // Protect super_admin: allow name/phone/password changes but lock role & status
        $target = $this->db->fetch("SELECT role_id, status FROM users WHERE id=?", [$id]);
        $targetIsSuperAdmin = $target && (int)$target['role_id'] === 1;

        // Password-only reset (from Reset Password modal)
        if ($this->input('_reset_password')) {
            $pwd = $this->input('password','');
            if (strlen($pwd) < 8) {
                Helper::setFlash('danger','Password must be at least 8 characters.');
                $this->redirect(APP_URL.'/admin/users');
                return;
            }
            $this->db->update('users', [
                'password'   => password_hash($pwd, PASSWORD_BCRYPT, ['cost'=>12]),
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id=?', [$id]);
            Helper::setFlash('success','Password reset successfully.');
            $this->redirect(APP_URL.'/admin/users');
            return;
        }

        // Full profile update (from edit page)
        $data = [
            'role_id'    => $targetIsSuperAdmin ? (int)$target['role_id'] : (int)$this->input('role_id'),
            'first_name' => Helper::sanitize($this->input('first_name','')),
            'last_name'  => Helper::sanitize($this->input('last_name','')),
            'phone'      => Helper::sanitize($this->input('phone','')),
            'status'     => $targetIsSuperAdmin ? $target['status'] : $this->input('status','active'),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        $pwd = $this->input('password','');
        if ($pwd) $data['password'] = password_hash($pwd, PASSWORD_BCRYPT, ['cost'=>12]);

        // Handle avatar upload
        if (!empty($_FILES['avatar']['tmp_name'])) {
            $file = $_FILES['avatar'];
            $allowed = ['image/jpeg','image/png','image/webp'];
            if (in_array($file['type'], $allowed) && $file['size'] <= 2 * 1024 * 1024) {
                $ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
                $filename = 'avatar_' . $id . '_' . time() . '.' . $ext;
                $dest     = $_SERVER['DOCUMENT_ROOT'] . '/zabibu-residence/public/uploads/avatars/' . $filename;
                if (move_uploaded_file($file['tmp_name'], $dest)) {
                    $data['avatar'] = $filename;
                }
            } else {
                Helper::setFlash('danger', 'Invalid image. Use JPG/PNG/WebP under 2MB.');
                $this->redirect(APP_URL.'/admin/users/'.$id.'/edit');
                return;
            }
        }

        $this->db->update('users', $data, 'id=?', [$id]);
        Helper::setFlash('success','User updated.');
        $this->redirect(APP_URL.'/admin/users');
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();
        if ((int)$id === (int)$_SESSION['user_id']) {
            Helper::setFlash('danger','You cannot delete your own account.'); $this->back(); return;
        }
        $target = $this->db->fetch("SELECT role_id FROM users WHERE id=?", [$id]);
        if ($target && (int)$target['role_id'] === 1) {
            Helper::setFlash('danger','The Super Admin account cannot be deactivated.');
            $this->redirect(APP_URL.'/admin/users');
            return;
        }
        $this->db->update('users', ['status'=>'inactive','updated_at'=>date('Y-m-d H:i:s')], 'id=?', [$id]);
        Helper::setFlash('success','User deactivated.');
        $this->redirect(APP_URL.'/admin/users');
    }
}
