<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Models\User;

class ProfileController extends Controller {
    
    protected $userModel;
    
    public function __construct() {
        parent::__construct();
        $this->userModel = new User();
    }
    
    public function index() {
        $this->requireAuth();
        
        $user = $this->userModel->find($_SESSION['user_id']);
        
        if (!$user) {
            $_SESSION['error'] = 'User not found';
            $this->redirect('/dashboard');
            return;
        }
        
        $this->render('profile/index', [
            'title' => 'My Profile',
            'user' => $user,
            'csrf_token' => $this->csrf_token()
        ]);
    }
    
    public function update() {
        $this->requireAuth();
        
        // Verify CSRF
        if (!isset($_POST['csrf_token']) || !\Security::validateCSRFToken($_POST['csrf_token'])) {
            $_SESSION['error'] = 'Invalid CSRF token';
            $this->redirect('/profile');
            return;
        }
        
        $user_id = $_SESSION['user_id'];
        $data = [
            'full_name' => $_POST['full_name'] ?? '',
            'email' => $_POST['email'] ?? ''
        ];
        
        // Validate
        if (empty($data['full_name']) || empty($data['email'])) {
            $_SESSION['error'] = 'All fields are required';
            $this->redirect('/profile');
            return;
        }
        
        // Check if email exists for another user
        $existing = $this->userModel->findByEmail($data['email']);
        if ($existing && $existing['id'] != $user_id) {
            $_SESSION['error'] = 'Email already in use by another account';
            $this->redirect('/profile');
            return;
        }
        
        $updated = $this->userModel->update($user_id, $data);
        
        if ($updated) {
            $_SESSION['full_name'] = $data['full_name'];
            $_SESSION['success'] = 'Profile updated successfully';
        } else {
            $_SESSION['error'] = 'Failed to update profile';
        }
        
        $this->redirect('/profile');
    }
}