<?php

declare(strict_types=1);

require_once __DIR__ . '/../app/config/bootstrap.php';
require_once __DIR__ . '/../app/core/Auth.php';
require_once __DIR__ . '/../app/core/DijikalaLayout.php';
require_once __DIR__ . '/../app/core/Csrf.php';
require_once __DIR__ . '/../app/core/MediaUpload.php';
require_once __DIR__ . '/../app/models/User.php';

Auth::startSession();
$user = Auth::user();
if (!$user) {
    header('Location: ' . appPath('/public/login.php'));
    exit;
}

$userModel = new User();
$row = $userModel->find((int)$user['id']);
if (!$row) {
    header('Location: ' . appPath('/public/logout.php'));
    exit;
}

$message = null;
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && Csrf::validate($_POST['_csrf'] ?? null)) {
    $data = [
        'full_name' => trim((string)($_POST['full_name'] ?? '')),
        'email' => trim((string)($_POST['email'] ?? '')),
        'phone' => trim((string)($_POST['phone'] ?? '')),
        'address' => trim((string)($_POST['address'] ?? '')),
        'profile_image' => null,
    ];
    if ($data['full_name'] === '') {
        $error = 'نام الزامی است.';
    } elseif (!empty($_FILES['profile_image']['name']) && (int)($_FILES['profile_image']['error'] ?? 0) !== UPLOAD_ERR_NO_FILE) {
        $up = MediaUpload::profileImage($_FILES['profile_image']);
        if (!$up['ok']) {
            $error = 'آپلود تصویر ناموفق بود.';
        } else {
            MediaUpload::deletePublicPath((string)($row['profile_image'] ?? ''));
            $data['profile_image'] = $up['path'] ?? null;
        }
    }
    if ($error === null && $userModel->updateProfile((int)$row['id'], $data)) {
        $message = 'پروفایل ذخیره شد.';
        $row = $userModel->find((int)$row['id']) ?? $row;
    } elseif ($error === null) {
        $error = 'ذخیره انجام نشد.';
    }
}

renderDijikalaShellStart('حساب کاربری | ' . APP_NAME, ['noindex' => true], '');
?>

<article class="container" style="padding:1.5rem 0 3rem;">
    <h2>حساب کاربری</h2>
    <?php if ($message): ?>
        <p style="color:#047857;margin:12px 0;"><?= htmlspecialchars($message) ?></p>
    <?php endif; ?>
    <?php if ($error): ?>
        <p style="color:#b91c1c;margin:12px 0;"><?= htmlspecialchars($error) ?></p>
    <?php endif; ?>
    <?php if (!empty($row['profile_image'])): ?>
        <p style="margin:12px 0;"><img src="<?= htmlspecialchars(appPath('/' . ltrim((string)$row['profile_image'], '/'))) ?>" alt="" style="max-width:120px;border-radius:8px;"></p>
    <?php endif; ?>
    <form class="c-form-account" method="post" enctype="multipart/form-data">
        <input type="hidden" name="_csrf" value="<?= htmlspecialchars(Csrf::token()) ?>">
        <div class="c-form-account__title">نام</div>
        <div class="c-form-account__row">
            <input class="c-ui-input__field c-ui-input__field--right-placeholder" name="full_name" required
                   value="<?= htmlspecialchars((string)$row['full_name']) ?>">
        </div>
        <div class="c-form-account__title">ایمیل</div>
        <div class="c-form-account__row">
            <input class="c-ui-input__field c-ui-input__field--right-placeholder" type="email" name="email"
                   value="<?= htmlspecialchars((string)($row['email'] ?? '')) ?>">
        </div>
        <div class="c-form-account__title">تلفن</div>
        <div class="c-form-account__row">
            <input class="c-ui-input__field c-ui-input__field--right-placeholder" name="phone"
                   value="<?= htmlspecialchars((string)($row['phone'] ?? '')) ?>">
        </div>
        <div class="c-form-account__title">آدرس</div>
        <div class="c-form-account__row">
            <textarea class="c-ui-input__field" name="address" rows="3"><?= htmlspecialchars((string)($row['address'] ?? '')) ?></textarea>
        </div>
        <div class="c-form-account__title">تصویر پروفایل</div>
        <div class="c-form-account__row">
            <input type="file" name="profile_image" accept="image/jpeg,image/png,image/webp">
        </div>
        <div class="c-form-account__row c-form-account__row--submit">
            <button class="btn-login" type="submit">ذخیره</button>
        </div>
    </form>
    <p style="margin-top:20px;"><a href="<?= htmlspecialchars(appPath('/public/logout.php')) ?>" class="btn-link-spoiler">خروج از حساب</a></p>
</article>

<?php
renderDijikalaShellEnd('profile', 'minimal');
Performance::finish('public.profile');
