<?php
// app/controllers/ProfileController.php

$appRoot = __DIR__ . '/..';
require_once $appRoot . '/models/User.php';

class ProfileController {
    private $pdo;
    private $userModel;

    public function __construct($pdo) {
        $this->pdo = $pdo;
        $this->userModel = new User($pdo);
    }

    public function index() {
        // Fetch current user data
        $stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = :id");
        $stmt->execute(['id' => $_SESSION['user_id']]);
        $user = $stmt->fetch();

        $pageTitle = "My Profile";
        $viewsPath = __DIR__ . '/../views';
        
        require_once $viewsPath . '/layouts/header.php';
        require_once $viewsPath . '/profile/index.php'; // We will create this next
        require_once $viewsPath . '/layouts/footer.php';
    }

    public function update() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $id = $_SESSION['user_id'];
            $name = $_POST['name'];
            $email = $_POST['email'];
            $newPassword = $_POST['new_password'];

            // 1. Update Basic Info
            $sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
            $params = ['name' => $name, 'email' => $email, 'id' => $id];

            // 2. Update Password (if provided)
            if (!empty($newPassword)) {
                $hash = password_hash($newPassword, PASSWORD_BCRYPT);
                $sql = "UPDATE users SET name = :name, email = :email, password = :pass WHERE id = :id";
                $params['pass'] = $hash;
            }

            $stmt = $this->pdo->prepare($sql);
            
            if ($stmt->execute($params)) {
                // Update Session Name
                $_SESSION['user_name'] = $name;
                echo "<script>alert('Profile updated successfully!'); window.location='/profile.php';</script>";
            } else {
                echo "<script>alert('Error updating profile.'); window.location='/profile.php';</script>";
            }
        }
    }
}
?>