<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../config.php';

if (isLoggedIn()) {
    $user_id = $_SESSION['user_id'];
    $user_type = $_SESSION['user_type'];
} else {
    redirect('../login.php');
}

$table_name = ($user_type === 'admin') ? 'admins' : 'representatives';
$id_field = 'id';

$message_data = getMessage();

// Handle POST requests for updating profile
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_general') {
        // Sanitize and validate inputs
        $username = trim($_POST['username']);
        $full_name = trim($_POST['full_name']);
        $email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL) ? trim($_POST['email']) : null;
        $mobile = trim($_POST['mobile']);

        // Check for unique username and email
        $stmt = $pdo->prepare("SELECT id FROM {$table_name} WHERE (username = ? OR email = ?) AND {$id_field} != ?");
        $stmt->execute([$username, $email, $user_id]);
        if ($stmt->fetch()) {
            setMessage('نام کاربری یا ایمیل قبلاً استفاده شده است.', 'error');
        } else {
            $sql = "UPDATE {$table_name} SET username = ?, full_name = ?, email = ?, mobile = ? WHERE {$id_field} = ?";
            $stmt = $pdo->prepare($sql);
            if ($stmt->execute([$username, $full_name, $email, $mobile, $user_id])) {
                setMessage('اطلاعات با موفقیت به‌روز شد.', 'success');
            } else {
                setMessage('خطا در به‌روزرسانی اطلاعات.', 'error');
            }
        }
    } elseif ($action === 'change_password') {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];

        $stmt = $pdo->prepare("SELECT password FROM {$table_name} WHERE {$id_field} = ?");
        $stmt->execute([$user_id]);
        $user_data = $stmt->fetch();

        if (verifyPassword($current_password, $user_data['password'])) {
            if ($new_password === $confirm_password) {
                $hashed_password = hashPassword($new_password);
                $stmt = $pdo->prepare("UPDATE {$table_name} SET password = ? WHERE {$id_field} = ?");
                if ($stmt->execute([$hashed_password, $user_id])) {
                    setMessage('رمز عبور با موفقیت تغییر کرد.', 'success');
                } else {
                    setMessage('خطا در تغییر رمز عبور.', 'error');
                }
            } else {
                setMessage('رمز عبور جدید و تکرار آن مطابقت ندارند.', 'error');
            }
        } else {
            setMessage('رمز عبور فعلی صحیح نیست.', 'error');
        }
    }
    redirect('profile.php');
    exit;
}


// Fetch user data for display
$stmt = $pdo->prepare("SELECT * FROM {$table_name} WHERE {$id_field} = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    setMessage('کاربر یافت نشد', 'error');
    redirect('../login.php');
}

$page_title = 'ویرایش پروفایل';
require_once '../includes/header.php';
?>

<?php if ($message_data): ?>
    <div class="alert alert-<?= htmlspecialchars($message_data['type']) ?> alert-dismissible fade show" role="alert">
        <?= htmlspecialchars($message_data['message']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>
<div class="row justify-content-center">
    <div class="col-lg-8 col-md-10">
        <div class="card admin-main-card">
            <div class="card-header">
                <h3 class="card-title mb-0"><?= htmlspecialchars($page_title) ?></h3>
                </div>
                <div class="card-body">
                    <ul class="nav nav-tabs" id="profileTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="general-tab" data-bs-toggle="tab" data-bs-target="#general" type="button" role="tab">اطلاعات عمومی</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="password-tab" data-bs-toggle="tab" data-bs-target="#password" type="button" role="tab">تغییر رمز عبور</button>
                        </li>
                    </ul>
                    <div class="tab-content pt-3" id="profileTabsContent">
                        <!-- General Information Tab -->
                        <div class="tab-pane fade show active" id="general" role="tabpanel">
                            <form action="profile.php" method="POST">
                                <input type="hidden" name="action" value="update_general">
                                <div class="mb-3">
                                    <label for="username" class="form-label">نام کاربری</label>
                                    <input type="text" class="form-control" id="username" name="username" value="<?= htmlspecialchars($user['username']) ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label for="full_name" class="form-label">نام کامل</label>
                                    <input type="text" class="form-control" id="full_name" name="full_name" value="<?= htmlspecialchars($user['full_name'] ?? '') ?>">
                                </div>
                                <div class="mb-3">
                                    <label for="email" class="form-label">ایمیل</label>
                                    <input type="email" class="form-control" id="email" name="email" value="<?= htmlspecialchars($user['email'] ?? '') ?>">
                                </div>
                                <div class="mb-3">
                                    <label for="mobile" class="form-label">شماره تلفن</label>
                                    <input type="text" class="form-control" id="mobile" name="mobile" value="<?= htmlspecialchars($user['mobile'] ?? '') ?>">
                                </div>
                                <button type="submit" class="btn btn-primary">ذخیره تغییرات</button>
                            </form>
                        </div>
                        <!-- Change Password Tab -->
                        <div class="tab-pane fade" id="password" role="tabpanel">
                            <form action="profile.php" method="POST">
                                <input type="hidden" name="action" value="change_password">
                                <div class="mb-3">
                                    <label for="current_password" class="form-label">رمز عبور فعلی</label>
                                    <input type="password" class="form-control" id="current_password" name="current_password" required>
                                </div>
                                <div class="mb-3">
                                    <label for="new_password" class="form-label">رمز عبور جدید</label>
                                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                                </div>
                                <div class="mb-3">
                                    <label for="confirm_password" class="form-label">تکرار رمز عبور جدید</label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                </div>
                                <button type="submit" class="btn btn-primary">تغییر رمز عبور</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

<?php require_once '../includes/footer.php'; ?>
