<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/PermissionManager.php';
require_once __DIR__ . '/components/navigation.php';
require_once __DIR__ . '/components/headers/page-header.php';

AuthManager::requireAuth();
TenantManager::initialize();

// Get current user and company
$user = AuthManager::getCurrentUser();
$company = TenantManager::getCurrentCompany();

function getWorkspaceQuery(?array $company): string
{
    if (!$company) {
        return '';
    }

    $slug = $company['username'] ?? $company['id'] ?? null;
    return $slug ? '?workspace=' . urlencode((string) $slug) : '';
}

$workspaceQuery = getWorkspaceQuery($company);
$memberSince = !empty($user['created_at']) ? date('M j, Y', strtotime($user['created_at'])) : null;
$workspaceHandle = $company['username'] ?? ($company['id'] ?? '—');
$workspaceName = $company['name'] ?? 'Workspace';

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? (AuthManager::isAuthenticated() ? ($_SESSION['theme_preference'] ?? 'dark') : 'dark');
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

// Handle profile and password updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update_profile') {
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';
        
        if (empty($name) || empty($email)) {
            $error = 'Name and email are required';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address';
        } else {
            try {
                $pdo = getPDO();
                $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
                $stmt->execute([$name, $email, $user['id']]);
                
                $_SESSION['success'] = 'Profile updated successfully!';
                header('Location: /profile.php' . $workspaceQuery);
                exit;
            } catch (Exception $e) {
                $error = 'Failed to update profile: ' . $e->getMessage();
            }
        }
    } elseif ($_POST['action'] === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmNewPassword = $_POST['confirm_new_password'] ?? '';

        if (empty($currentPassword) || empty($newPassword) || empty($confirmNewPassword)) {
            $error = 'All password fields are required';
        } elseif (strlen($newPassword) < 8) {
            $error = 'New password must be at least 8 characters';
        } elseif ($newPassword !== $confirmNewPassword) {
            $error = 'New passwords do not match';
        } else {
            try {
                $pdo = getPDO();
                $stmt = $pdo->prepare("SELECT password_hash FROM users WHERE id = ?");
                $stmt->execute([$user['id']]);
                $row = $stmt->fetch();

                if (!$row || !password_verify($currentPassword, $row['password_hash'] ?? '')) {
                    $error = 'Current password is incorrect';
                } else {
                    $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
                    $updateStmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
                    $updateStmt->execute([$newHash, $user['id']]);

                    $_SESSION['success'] = 'Password updated successfully!';
                    header('Location: /profile.php' . $workspaceQuery);
                    exit;
                }
            } catch (Exception $e) {
                $error = 'Failed to update password: ' . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php renderNavigationNew('Profile', $currentTheme); ?>

<div class="main-container">
    <?php
    $breadcrumbs = [
        [
            'label' => 'Profile',
            'url' => '/profile.php',
            'icon' => 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z',
        ],
    ];
    $actions = [
        [
            'label' => 'Billing',
            'url' => '/billing.php' . $workspaceQuery,
            'type' => 'primary',
            'icon' => 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z',
        ],
    ];
    renderPageHeader(
        breadcrumbs: $breadcrumbs,
        currentPage: 'Settings',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <?php if (isset($error)): ?>
            <div class="status-banner error" style="margin-bottom: 16px;">
                <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm-.75-11.5a.75.75 0 011.5 0v5a.75.75 0 01-1.5 0v-5zm.75 8a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"></path>
                </svg>
                <span><?= htmlspecialchars($error) ?></span>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['success'])): ?>
            <div class="status-banner success" style="margin-bottom: 16px;">
                <svg style="width: 14px; height: 14px;" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                </svg>
                <span><?= htmlspecialchars($_SESSION['success']) ?></span>
            </div>
            <?php unset($_SESSION['success']); ?>
        <?php endif; ?>

        <div class="dash-section">
            <section class="profile-hero">
                <div>
                    <p class="section-title">Account Center</p>
                    <h1 class="profile-hero__title">Hi <?= htmlspecialchars($user['name'] ?? 'there') ?>, keep your details current.</h1>
                    <p class="profile-hero__subtitle">Every update here syncs across proposals, invoices, and workspaces.</p>
                </div>
                <?php if ($memberSince): ?>
                    <div class="profile-hero__meta">
                        <span class="profile-hero__label">Member since</span>
                        <span class="profile-hero__value"><?= $memberSince ?></span>
                    </div>
                <?php endif; ?>
            </section>
        </div>

        <div class="dash-section">
            <div class="profile-grid">
                <section class="profile-card profile-card--span2">
                    <div class="profile-card__header">
                        <div class="profile-card__icon">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
                            </svg>
                        </div>
                        <div>
                            <h2 class="profile-card__title">Personal information</h2>
                            <p class="profile-card__subtitle">Keep your name and email accurate for billing and notifications.</p>
                        </div>
                    </div>

                    <form method="POST" class="profile-form">
                        <input type="hidden" name="action" value="update_profile">
                        <div class="form-field">
                            <label class="form-label" for="name">Full name</label>
                            <input id="name" type="text" name="name" value="<?= htmlspecialchars($user['name'] ?? '') ?>" required class="form-input">
                        </div>
                        <div class="form-field">
                            <label class="form-label" for="email">Email</label>
                            <input id="email" type="email" name="email" value="<?= htmlspecialchars($user['email'] ?? '') ?>" required class="form-input">
                            <p class="form-hint">
                                <svg class="form-hint__icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                                </svg>
                                <?= htmlspecialchars($user['email_verified_at'] ? 'Email verified' : 'Primary contact email') ?>
                            </p>
                        </div>
                        <div class="form-actions">
                            <button type="submit" class="btn-emerald">
                                <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                                </svg>
                                Save personal info
                            </button>
                        </div>
                    </form>
                </section>

                <section class="profile-card">
                    <div class="profile-card__header">
                        <div class="profile-card__icon">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 11c1.657 0 3-1.343 3-3V6a3 3 0 10-6 0v2c0 1.657 1.343 3 3 3z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 11h10a2 2 0 012 2v5a2 2 0 01-2 2H7a2 2 0 01-2-2v-5a2 2 0 012-2z"></path>
                            </svg>
                        </div>
                        <div>
                            <h2 class="profile-card__title">Change password</h2>
                            <p class="profile-card__subtitle">Use a mix of letters, numbers, and symbols. Minimum 8 characters.</p>
                        </div>
                    </div>

                    <form method="POST" class="profile-form">
                        <input type="hidden" name="action" value="change_password">
                        <div class="form-field">
                            <label class="form-label" for="current_password">Current password</label>
                            <input id="current_password" type="password" name="current_password" required class="form-input" placeholder="••••••••">
                        </div>
                        <div class="form-field">
                            <label class="form-label" for="new_password">New password</label>
                            <input id="new_password" type="password" name="new_password" required class="form-input" placeholder="At least 8 characters">
                        </div>
                        <div class="form-field">
                            <label class="form-label" for="confirm_new_password">Confirm new password</label>
                            <input id="confirm_new_password" type="password" name="confirm_new_password" required class="form-input" placeholder="Repeat new password">
                        </div>
                        <div class="form-actions">
                            <button type="submit" class="btn-secondary">
                                <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 11c1.657 0 3-1.343 3-3V6a3 3 0 10-6 0v2c0 1.657 1.343 3 3 3z"></path>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 11h10a2 2 0 012 2v5a2 2 0 01-2 2H7a2 2 0 01-2-2v-5a2 2 0 012-2z"></path>
                                </svg>
                                Update password
                            </button>
                        </div>
                    </form>
                </section>

            </div>
        </div>
    </div>
</div>

<div class="main-container--end"></div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', window.openAppSidebar);
    }
});
</script>
</body>
</html>
