<?php
session_start();
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/classes/User.php';

redirect_if_not_logged_in('index.php');

$userManager = new User($pdo);
$errors = [];

try {
    $userDetails = $userManager->getUserDetails((int) $_SESSION['user_id']);
} catch (Exception $e) {
    set_message('Unable to load your profile right now. Please try again later.', 'danger');
    header('Location: index.php');
    exit();
}

if (!$userDetails) {
    set_message('We could not find your account record. Contact support.', 'danger');
    header('Location: index.php');
    exit();
}

$personId = (int) $userDetails['fkisp_id_of'];
$role = $_SESSION['user_status'] ?? '';

$layoutMap = [
    'DAC Staff' => [
        'header' => 'includes/header_admin.php',
        'nav' => 'includes/nav_admin.php',
        'footer' => 'includes/footer_admin.php',
        'dashboard' => 'admin/dashboard.php',
        'badge' => 'bg-danger',
    ],
    'Data Owner' => [
        'header' => 'includes/header_owner.php',
        'nav' => 'includes/nav_owner.php',
        'footer' => 'includes/footer_owner.php',
        'dashboard' => 'data_owner/dashboard.php',
        'badge' => 'bg-info',
    ],
    'Data Contributor' => [
        'header' => 'includes/header_contributor.php',
        'nav' => 'includes/nav_contributor.php',
        'footer' => 'includes/footer_contributor.php',
        'dashboard' => 'data_hybrid/dashboard.php',
        'badge' => 'bg-primary',
    ],
    'Data User' => [
        'header' => 'includes/header_user.php',
        'nav' => 'includes/nav_user.php',
        'footer' => 'includes/footer_user.php',
        'dashboard' => 'data_user/dashboard.php',
        'badge' => 'bg-success',
    ],
];

$layout = $layoutMap[$role] ?? $layoutMap['Data User'];

$sexOptions = ['Male', 'Female', 'Other'];
$maritalOptions = ['Single', 'Married', 'Divorced', 'Widowed'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $payload = [
        'isp_firstname_en' => trim($_POST['isp_firstname_en'] ?? ''),
        'isp_lastname_en' => trim($_POST['isp_lastname_en'] ?? ''),
        'isp_sex' => trim($_POST['isp_sex'] ?? ''),
        'isp_dob' => trim($_POST['isp_dob'] ?? ''),
        'isp_pob' => trim($_POST['isp_pob'] ?? ''),
        'isp_nationality' => trim($_POST['isp_nationality'] ?? ''),
        'isp_marital_status' => trim($_POST['isp_marital_status'] ?? ''),
        'isp_phone_number' => trim($_POST['isp_phone_number'] ?? ''),
        'isp_email' => trim($_POST['isp_email'] ?? ''),
        'isp_telegram' => trim($_POST['isp_telegram'] ?? ''),
        'isp_note' => trim($_POST['isp_note'] ?? ''),
    ];
    if ($payload['isp_firstname_en'] === '' || $payload['isp_lastname_en'] === '') {
        $errors[] = 'First name and last name are required.';
    }
    if ($payload['isp_sex'] === '' || !in_array($payload['isp_sex'], $sexOptions, true)) {
        $errors[] = 'Please select a valid gender.';
    }
    if ($payload['isp_dob'] === '') {
        $errors[] = 'Date of birth is required.';
    }
    if ($payload['isp_marital_status'] !== '' && !in_array($payload['isp_marital_status'], $maritalOptions, true)) {
        $errors[] = 'Please select a valid marital status.';
    }
    if ($payload['isp_email'] !== '' && !filter_var($payload['isp_email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please provide a valid email address.';
    }

    if (empty($errors)) {
        try {
            $userManager->updatePersonInfo($personId, $payload, (int) $_SESSION['user_id']);
            set_message('Your profile was updated successfully.', 'success');
            header('Location: profile.php');
            exit();
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }

    $userDetails = array_merge($userDetails, $payload);
}

$lastUpdated = $userDetails['isp_mod_datetime'] ?? $userDetails['isp_reg_datetime'] ?? null;
$displayLastUpdated = $lastUpdated ? date('M j, Y', strtotime($lastUpdated)) : 'Unknown';
$dashboardLink = $layout['dashboard'];
?>
<!DOCTYPE html>
<html lang="en">
<?php include_once __DIR__ . '/' . $layout['header']; ?>

<body>
    <div class="wrapper">
        <?php include_once __DIR__ . '/' . $layout['nav']; ?>
        <div class="main-content">
            <nav class="navbar navbar-expand-lg navbar-light bg-white mb-4 shadow-sm rounded-3">
                <div class="container-fluid">
                    <div>
                        <span class="badge <?php echo htmlspecialchars($layout['badge']); ?> text-white me-2">
                            <?php echo htmlspecialchars($role ?: 'Data User'); ?>
                        </span>
                        <span class="navbar-brand mb-0 fw-semibold">My Profile</span>
                    </div>
                    <div class="text-muted small">
                        Last updated: <?php echo htmlspecialchars($displayLastUpdated); ?>
                    </div>
                </div>
            </nav>

            <?php
            if (isset($_SESSION['message'])) {
                echo '<div class="alert alert-' . $_SESSION['message_type'] . ' alert-dismissible fade show rounded" role="alert">'
                    . htmlspecialchars($_SESSION['message'])
                    . '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>';
                unset($_SESSION['message'], $_SESSION['message_type']);
            }

            if (!empty($errors)) {
                echo '<div class="alert alert-danger rounded"><ul class="mb-0">';
                foreach ($errors as $error) {
                    echo '<li>' . htmlspecialchars($error) . '</li>';
                }
                echo '</ul></div>';
            }
            ?>

            <div class="alert alert-info border-0 shadow-sm rounded-3">
                <div class="d-flex align-items-center">
                    <i class="fas fa-user-shield fa-2x me-3 text-primary"></i>
                    <div>
                        <h5 class="mb-1">Keep your profile current</h5>
                        <p class="mb-0">Accurate contact and identity details help the Data Access Committee approve requests quickly and keep audit logs clean.</p>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 mt-4">
                <div class="card-body p-4">
                    <form method="POST" novalidate>
                        <div class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_firstname_en">First Name (EN)</label>
                                <input type="text" class="form-control rounded" id="isp_firstname_en" name="isp_firstname_en" value="<?php echo htmlspecialchars($userDetails['isp_firstname_en'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_lastname_en">Last Name (EN)</label>
                                <input type="text" class="form-control rounded" id="isp_lastname_en" name="isp_lastname_en" value="<?php echo htmlspecialchars($userDetails['isp_lastname_en'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_sex">Gender</label>
                                <select class="form-select rounded" id="isp_sex" name="isp_sex" required>
                                    <option value="">Select gender</option>
                                    <?php foreach ($sexOptions as $option): ?>
                                        <option value="<?php echo htmlspecialchars($option); ?>" <?php echo (($userDetails['isp_sex'] ?? '') === $option) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($option); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_dob">Date of Birth</label>
                                <input type="date" class="form-control rounded" id="isp_dob" name="isp_dob" value="<?php echo htmlspecialchars($userDetails['isp_dob'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_pob">Place of Birth</label>
                                <input type="text" class="form-control rounded" id="isp_pob" name="isp_pob" value="<?php echo htmlspecialchars($userDetails['isp_pob'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_nationality">Nationality</label>
                                <input type="text" class="form-control rounded" id="isp_nationality" name="isp_nationality" value="<?php echo htmlspecialchars($userDetails['isp_nationality'] ?? 'Cambodian'); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_marital_status">Marital Status</label>
                                <select class="form-select rounded" id="isp_marital_status" name="isp_marital_status">
                                    <option value="">Select status</option>
                                    <?php foreach ($maritalOptions as $option): ?>
                                        <option value="<?php echo htmlspecialchars($option); ?>" <?php echo (($userDetails['isp_marital_status'] ?? '') === $option) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($option); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_phone_number">Phone Number</label>
                                <input type="text" class="form-control rounded" id="isp_phone_number" name="isp_phone_number" value="<?php echo htmlspecialchars($userDetails['isp_phone_number'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_email">Email Address</label>
                                <input type="email" class="form-control rounded" id="isp_email" name="isp_email" value="<?php echo htmlspecialchars($userDetails['isp_email'] ?? ''); ?>">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label fw-semibold" for="isp_telegram">Telegram / Messaging ID</label>
                                <input type="text" class="form-control rounded" id="isp_telegram" name="isp_telegram" value="<?php echo htmlspecialchars($userDetails['isp_telegram'] ?? ''); ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label fw-semibold" for="isp_note">Notes (optional)</label>
                                <textarea class="form-control rounded" id="isp_note" name="isp_note" rows="3"><?php echo htmlspecialchars($userDetails['isp_note'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        <div class="d-flex flex-wrap gap-2 mt-4">
                            <button type="submit" class="btn btn-success rounded-pill px-4">
                                <i class="fas fa-save me-2"></i>Save Changes
                            </button>
                            <a href="<?php echo htmlspecialchars($dashboardLink); ?>" class="btn btn-outline-secondary rounded-pill px-4">
                                <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php include_once __DIR__ . '/' . $layout['footer']; ?>
</body>
</html>
