<?php
require_once __DIR__ . '/../../../Models/Database.php';

class ProfileController {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    public function index() {
        $adminId = $_SESSION['admin_id'];
        $stmt = $this->db->prepare("SELECT * FROM admins WHERE id = ?");
        $stmt->execute([$adminId]);
        $admin = $stmt->fetch();

        require __DIR__ . '/../../../../views/admin/profile/index.php';
    }

    public function update() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
        
        $adminId = $_SESSION['admin_id'];
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';
        
        if (empty($name) || empty($email)) {
            header("Location: ?page=profile&error=Name and Email are required");
            exit;
        }

        $stmt = $this->db->prepare("UPDATE admins SET name = ?, email = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$name, $email, $adminId]);
        
        $_SESSION['admin_name'] = $name;
        header("Location: ?page=profile&success=Profile updated successfully");
        exit;
    }

    public function changePassword() {
        require __DIR__ . '/../../../../views/admin/profile/change_password.php';
    }

    public function updatePassword() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;

        $adminId = $_SESSION['admin_id'];
        $oldPassword = $_POST['old_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';

        if (empty($oldPassword) || empty($newPassword)) {
            header("Location: ?page=change_password&error=All fields are required");
            exit;
        }

        if ($newPassword !== $confirmPassword) {
            header("Location: ?page=change_password&error=Passwords do not match");
            exit;
        }

        $stmt = $this->db->prepare("SELECT password FROM admins WHERE id = ?");
        $stmt->execute([$adminId]);
        $admin = $stmt->fetch();

        if (!password_verify($oldPassword, $admin['password'])) {
            header("Location: ?page=change_password&error=Incorrect current password");
            exit;
        }

        $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
        $stmt = $this->db->prepare("UPDATE admins SET password = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$hashedPassword, $adminId]);

        header("Location: ?page=change_password&success=Password changed successfully");
        exit;
    }
}
