<?php
class ProfileController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $user = $this->db->fetch("SELECT u.*, r.name as role_name FROM users u LEFT JOIN roles r ON u.role_id=r.id WHERE u.id=?", [Auth::user()['id']]);
        require 'app/views/profile/index.php';
    }

    public function update() {
        CSRF::verify(); $uid = Auth::user()['id'];
        $v = new Validator($_POST); $v->required('first_name')->required('last_name')->required('email');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=profile'); }
        $this->db->update('users', [
            'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'],
            'email' => $_POST['email'], 'phone' => $_POST['phone'] ?? null,
        ], 'id = ?', [$uid]);
        flash('success', 'Profile updated.'); redirect('?page=profile');
    }

    public function password() {
        CSRF::verify(); $uid = Auth::user()['id'];
        if (empty($_POST['current_password']) || empty($_POST['new_password'])) {
            flash('error', 'All password fields required.'); redirect('?page=profile'); return;
        }
        $user = $this->db->fetch("SELECT password FROM users WHERE id=?", [$uid]);
        if (!password_verify($_POST['current_password'], $user['password'])) {
            flash('error', 'Current password is incorrect.'); redirect('?page=profile'); return;
        }
        if ($_POST['new_password'] !== $_POST['confirm_password']) {
            flash('error', 'Passwords do not match.'); redirect('?page=profile'); return;
        }
        if (strlen($_POST['new_password']) < 8) {
            flash('error', 'Password must be at least 8 characters.'); redirect('?page=profile'); return;
        }
        $this->db->update('users', ['password' => password_hash($_POST['new_password'], PASSWORD_DEFAULT)], 'id = ?', [$uid]);
        flash('success', 'Password changed.'); redirect('?page=profile');
    }
}
