<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../lib/auth.php';
require_once __DIR__ . '/../../lib/csrf.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

requireLogin();

$pageTitle = 'Account Settings';
$siteName  = 'Crop Monitor';

$pdo     = getDBConnection();
$userId  = getCurrentUserId();
$user    = getCurrentUser();

$errors  = [];
$success = false;

// Handle profile update POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['form-save'])) {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid CSRF token.';
    } else {
        $fields = ['fullname', 'company', 'phone', 'mobilephone', 'email', 'address', 'city', 'state', 'zip', 'country', 'industry', 'role'];
        $set    = [];
        $values = [];
        foreach ($fields as $f) {
            $set[]    = "`$f` = ?";
            $values[] = trim($_POST[$f] ?? '');
        }
        $values[] = $userId;

        try {
            $pdo->prepare('UPDATE users SET ' . implode(', ', $set) . ' WHERE id = ?')->execute($values);
            $success = true;
            // Refresh session name
            $_SESSION['user_name'] = trim($_POST['fullname'] ?? '');
        } catch (\PDOException $e) {
            $errors[] = 'Failed to update profile.';
        }
    }
}

// Load current profile data from users table
$profile = [];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
$stmt->execute([$userId]);
$profile = $stmt->fetch() ?: [];

$h = fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

include __DIR__ . '/../../layouts/header.php';
include __DIR__ . '/../../layouts/navbar.php';
?>

<div id="layoutSidenav">
    <div id="layoutSidenav_nav">
        <?php include __DIR__ . '/../../layouts/sidebar.php'; ?>
    </div>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">
                <h1 class="mt-4"><?= $h($pageTitle) ?></h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="/dashboard/dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Account Settings</li>
                </ol>

                <?php if ($success): ?>
                    <div class="alert alert-success">Profile updated successfully.</div>
                <?php endif; ?>
                <?php foreach ($errors as $err): ?>
                    <div class="alert alert-danger"><?= $h($err) ?></div>
                <?php endforeach; ?>

                <div class="row">
                    <div class="col-sm-3">
                        <div class="text-center">
                            <img src="/client-assets/images/avatar-placeholder.png"
                                 class="img-circle img-fluid img-thumbnail mb-2" alt="avatar"
                                 style="max-width:150px">
                        </div>
                        <div class="alert alert-success mt-2" role="alert">
                            Your Account level is: <b>FREE</b>
                            <a href="#" class="alert-link">Upgrade Account</a>
                        </div>
                    </div>

                    <div class="col-sm-9">
                        <ul class="nav nav-tabs" id="settingsTabs">
                            <li class="nav-item">
                                <a class="nav-link active" data-bs-toggle="tab" href="#contact-details">Your Details</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" data-bs-toggle="tab" href="#change-password">Change Password</a>
                            </li>
                        </ul>

                        <div class="tab-content mt-3">
                            <!-- Contact Details Tab -->
                            <div class="tab-pane fade show active" id="contact-details">
                                <form class="form" action="" method="post" id="registrationForm">
                                    <input type="hidden" name="csrf_token" value="<?= $h(generateCsrfToken()) ?>">
                                    <input type="hidden" name="form-save" value="1">

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Name</label>
                                            <input type="text" class="form-control" name="fullname"
                                                   value="<?= $h($profile['fullname'] ?? '') ?>">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Company</label>
                                            <input type="text" class="form-control" name="company"
                                                   value="<?= $h($profile['company'] ?? '') ?>">
                                        </div>
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Phone</label>
                                            <input type="text" class="form-control" name="phone"
                                                   value="<?= $h($profile['phone'] ?? '') ?>">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Mobile</label>
                                            <input type="text" class="form-control" name="mobilephone"
                                                   value="<?= $h($profile['mobilephone'] ?? '') ?>">
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Email</label>
                                        <input type="email" class="form-control" name="email"
                                               value="<?= $h($profile['email'] ?? $user['email'] ?? '') ?>">
                                    </div>

                                    <div class="mb-3">
                                        <label class="form-label">Address</label>
                                        <input type="text" class="form-control" name="address"
                                               value="<?= $h($profile['address'] ?? '') ?>">
                                    </div>

                                    <div class="row mb-3">
                                        <div class="col-md-3">
                                            <label class="form-label">City</label>
                                            <input type="text" class="form-control" name="city"
                                                   value="<?= $h($profile['city'] ?? '') ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">State</label>
                                            <input type="text" class="form-control" name="state"
                                                   value="<?= $h($profile['state'] ?? '') ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Postcode</label>
                                            <input type="text" class="form-control" name="zip"
                                                   value="<?= $h($profile['zip'] ?? '') ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Country</label>
                                            <input type="text" class="form-control" name="country"
                                                   value="<?= $h($profile['country'] ?? '') ?>">
                                        </div>
                                    </div>

                                    <hr>
                                    <h5>Industry Details</h5>

                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Industry</label>
                                            <select class="form-select" name="industry">
                                                <?php foreach (['Broadacre','Viticulture','Horticulture','Permaculture','Dairy'] as $opt): ?>
                                                <option value="<?= $h($opt) ?>" <?= ($profile['industry'] ?? '') === $opt ? 'selected' : '' ?>>
                                                    <?= $h($opt) ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Role</label>
                                            <select class="form-select" name="role">
                                                <?php foreach (['Manager','Viticulturist','Horticulturist','Permaculturist','Irrigation Manager'] as $opt): ?>
                                                <option value="<?= $h($opt) ?>" <?= ($profile['role'] ?? '') === $opt ? 'selected' : '' ?>>
                                                    <?= $h($opt) ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <button class="btn btn-success" type="submit">Save</button>
                                    <button class="btn btn-warning ms-2" type="reset">Reset</button>
                                </form>
                            </div>

                            <!-- Change Password Tab -->
                            <div class="tab-pane fade" id="change-password">
                                <p class="text-muted">
                                    To change your password, please use the
                                    <a href="/login/change-password.php">Change Password</a> page.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <?php include __DIR__ . '/../../layouts/footer.php'; ?>
    </div>
</div>
