<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Models\ProfileField;
use App\Models\AuditLog;

class ProfileFieldController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function index()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $model = new ProfileField();
        $fields = $model->getAllWithOrder();
        $this->view('profile_fields/index', ['fields' => $fields]);
    }

    public function create()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $this->view('profile_fields/form', ['field' => null]);
    }

    public function store()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }

        $model = new ProfileField();
        $label = trim($_POST['label'] ?? '');
        if (empty($label)) {
            $_SESSION['error'] = 'Field label is required';
            $this->redirect('/profile-fields/create');
        }

        $fieldName = $model->generateFieldName($label);
        $maxOrder = $this->db->query("SELECT COALESCE(MAX(sort_order), -1) + 1 as next FROM profile_fields")->fetch(\PDO::FETCH_OBJ)->next;

        $model->create([
            'label' => $label,
            'field_name' => $fieldName,
            'field_type' => $_POST['field_type'] ?? 'text',
            'options' => $_POST['options'] ?? null,
            'placeholder' => $_POST['placeholder'] ?? null,
            'help_text' => $_POST['help_text'] ?? null,
            'is_required' => isset($_POST['is_required']) ? 1 : 0,
            'sort_order' => $maxOrder,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'show_in_directory' => isset($_POST['show_in_directory']) ? 1 : 0,
        ]);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'profile_field.create', 'profile_fields', $this->db->lastInsertId(), "Created profile field: {$label}");

        $_SESSION['success'] = "Profile field '{$label}' created";
        $this->redirect('/profile-fields');
    }

    public function edit($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $id = $params['id'] ?? null;
        $model = new ProfileField();
        $field = $model->find($id);

        if (!$field) {
            $_SESSION['error'] = 'Field not found';
            $this->redirect('/profile-fields');
        }

        $this->view('profile_fields/form', ['field' => $field]);
    }

    public function update($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }

        $id = $params['id'] ?? null;
        $model = new ProfileField();
        $field = $model->find($id);

        if (!$field) {
            $_SESSION['error'] = 'Field not found';
            $this->redirect('/profile-fields');
        }

        $data = [
            'label' => $_POST['label'] ?? $field->label,
            'field_type' => $_POST['field_type'] ?? $field->field_type,
            'options' => $_POST['options'] ?? null,
            'placeholder' => $_POST['placeholder'] ?? null,
            'help_text' => $_POST['help_text'] ?? null,
            'is_required' => isset($_POST['is_required']) ? 1 : 0,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'show_in_directory' => isset($_POST['show_in_directory']) ? 1 : 0,
        ];

        $model->update($id, $data);

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'profile_field.update', 'profile_fields', $id, "Updated profile field: {$data['label']}");

        $_SESSION['success'] = "Profile field '{$data['label']}' updated";
        $this->redirect('/profile-fields');
    }

    public function delete($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }

        $id = $params['id'] ?? null;
        $model = new ProfileField();
        $field = $model->find($id);

        if ($field) {
            $this->db->prepare("DELETE FROM profile_field_values WHERE field_id = ?")->execute([$id]);
            $model->delete($id);

            $audit = new AuditLog();
            $audit->log(Auth::id(), 'profile_field.delete', 'profile_fields', $id, "Deleted profile field: {$field->label}");
            $_SESSION['success'] = "Field '{$field->label}' deleted";
        }

        $this->redirect('/profile-fields');
    }

    public function reorder()
    {
        if (Auth::user()->role !== 'admin') {
            $this->json(['error' => 'Access denied'], 403);
        }

        $ids = $_POST['ids'] ?? [];
        if (!empty($ids)) {
            $model = new ProfileField();
            $model->updateOrder($ids);
        }

        $this->json(['success' => true]);
    }
}
