<?php
/**
 * IBVTE College – Change Password
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

$collegePage = 'password';
Auth()->requireRole(['college']);

$db   = DB();
$user = Auth()->getUser();
$msg  = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current  = $_POST['current_password']  ?? '';
    $new      = $_POST['new_password']      ?? '';
    $confirm  = $_POST['confirm_password']  ?? '';

    if (strlen($new) < 8) {
        $msg = ['type' => 'danger', 'text' => 'New password must be at least 8 characters.'];
    } elseif ($new !== $confirm) {
        $msg = ['type' => 'danger', 'text' => 'New password and confirmation do not match.'];
    } else {
        $result = Auth()->changePassword($user['id'], $current, $new);
        if ($result['success']) {
            // Log activity
            $db->insert('college_activity_logs', [
                'college_id'  => $user['id'],
                'action'      => 'PASSWORD_CHANGED',
                'description' => 'College password was changed successfully.',
                'entity_type' => 'user',
                'entity_id'   => $user['id'],
                'ip_address'  => $_SERVER['REMOTE_ADDR'] ?? '',
            ]);
            $msg = ['type' => 'success', 'text' => '✅ Password changed successfully! Please use your new password on next login.'];
        } else {
            $msg = ['type' => 'danger', 'text' => '❌ ' . $result['message']];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Password – <?= APP_SHORT_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        /* ── College Sidebar ─────────────────────────── */
        :root { --primary:#3b0b7c; --secondary:#6c4ab6; }
        .college-sidebar {
            width: 250px;
            background: white;
            min-height: 100vh;
            position: fixed;
            top: 0; left: 0;
            display: flex;
            flex-direction: column;
            box-shadow: 3px 0 15px rgba(59,11,124,0.08);
            z-index: 1040;
            transition: transform .3s;
        }
        .sidebar-brand {
            padding: 28px 20px 20px;
            text-align: center;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
        }
        .sidebar-logo {
            width: 68px; height: 68px;
            border-radius: 50%;
            border: 3px solid rgba(255,255,255,.35);
            object-fit: cover;
            margin-bottom: 12px;
        }
        .sidebar-college-name {
            color: white;
            font-weight: 700;
            font-size: .9rem;
            line-height: 1.3;
        }
        .sidebar-code {
            color: rgba(255,255,255,.65);
            font-size: .75rem;
            margin-top: 4px;
        }
        .sidebar-nav {
            flex: 1;
            padding: 16px 12px;
            overflow-y: auto;
        }
        .sidebar-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 11px 16px;
            border-radius: 10px;
            color: #555;
            text-decoration: none;
            font-size: .9rem;
            font-weight: 500;
            margin-bottom: 4px;
            transition: background .2s, color .2s, transform .15s;
        }
        .sidebar-link:hover {
            background: #f0ebf8;
            color: var(--primary);
            transform: translateX(3px);
        }
        .sidebar-link.active {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white !important;
            box-shadow: 0 4px 12px rgba(59,11,124,.25);
        }
        .sidebar-icon { width: 18px; text-align: center; flex-shrink: 0; font-size: .95rem; }
        .sidebar-footer { padding: 12px; border-top: 1px solid #f0f0f0; }
        .sidebar-logout { color: #dc3545 !important; }
        .sidebar-logout:hover { background: #fff0f0; color: #dc3545 !important; }
        .college-main { margin-left: 250px; padding: 30px; min-height: 100vh; background: #f8f9fa; }
        @media (max-width: 768px) {
            .college-sidebar { transform: translateX(-100%); }
            .college-sidebar.open { transform: translateX(0); }
            .college-main { margin-left: 0; padding: 20px 15px; }
            .mobile-menu-btn { display: flex !important; }
        }

        :root { --primary:#3b0b7c; --secondary:#6c4ab6; }
        body { background:#f8f9fa; font-family:'Segoe UI',sans-serif; }
        .sidebar { width:250px; background:white; min-height:100vh; position:fixed; box-shadow:2px 0 10px rgba(0,0,0,.05); z-index:1000; }
        .main-content { margin-left:250px; padding:30px; }
        .nav-link-item { padding:12px 25px; display:block; color:#555; text-decoration:none; transition:.3s; margin:4px 15px; border-radius:10px; }
        .nav-link-item:hover,.nav-link-item.active { background:var(--primary); color:white; }
        .pwd-card { max-width:520px; border-radius:18px; border:none; box-shadow:0 8px 30px rgba(0,0,0,.08); }
        .pwd-header { background:linear-gradient(135deg,var(--primary),var(--secondary)); color:white; border-radius:18px 18px 0 0; padding:30px; }
        .strength-bar { height:6px; border-radius:3px; transition:all .3s; }
        @media(max-width:768px){.sidebar{display:none;}.main-content{margin-left:0;}}
    </style>
</head>
<body>

<?php include __DIR__ . '/../includes/college_sidebar.php'; ?>

<!-- Mobile menu button -->
<button class="btn btn-sm mobile-menu-btn d-md-none"
        style="display:none;position:fixed;top:15px;left:15px;z-index:1050;background:var(--primary);color:white;border-radius:8px;padding:8px 12px;"
        onclick="toggleSidebar()" id="mobileMenuBtn">
    <i class="fas fa-bars"></i>
</button>
<div class="overlay d-none" id="sidebarOverlay" onclick="toggleSidebar()"
     style="position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:1039;"></div>

<div class="college-main">
    <div class="mb-4">
        <h3 class="fw-bold">Change Password</h3>
        <p class="text-muted">Update your college portal login password</p>
    </div>

    <div class="pwd-card card">
        <div class="pwd-header">
            <h5 class="mb-1"><i class="fas fa-shield-alt me-2"></i>Secure Password Change</h5>
            <p class="mb-0 opacity-75 small">Use a strong password with letters, numbers &amp; symbols</p>
        </div>
        <div class="card-body p-4">

            <?php if ($msg): ?>
                <div class="alert alert-<?= $msg['type'] ?> alert-dismissible fade show rounded-3">
                    <?= $msg['text'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <form method="POST" id="pwdForm">
                <div class="mb-4">
                    <label class="fw-bold small mb-1">Current Password</label>
                    <div class="input-group">
                        <input type="password" name="current_password" id="cur_pass"
                               class="form-control rounded-start-3" placeholder="Enter current password" required>
                        <button type="button" class="btn btn-outline-secondary" onclick="toggleVis('cur_pass',this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="fw-bold small mb-1">New Password</label>
                    <div class="input-group">
                        <input type="password" name="new_password" id="new_pass"
                               class="form-control rounded-start-3" placeholder="Min 8 characters"
                               oninput="checkStrength(this.value)" required>
                        <button type="button" class="btn btn-outline-secondary" onclick="toggleVis('new_pass',this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <div class="mt-2">
                        <div class="strength-bar w-0 bg-danger" id="strengthBar"></div>
                        <small id="strengthLabel" class="text-muted"></small>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="fw-bold small mb-1">Confirm New Password</label>
                    <div class="input-group">
                        <input type="password" name="confirm_password" id="con_pass"
                               class="form-control rounded-start-3" placeholder="Repeat new password"
                               oninput="checkMatch()" required>
                        <button type="button" class="btn btn-outline-secondary" onclick="toggleVis('con_pass',this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                    <small id="matchLabel" class="text-muted"></small>
                </div>

                <button type="submit" class="btn w-100 py-2 fw-bold text-white"
                        style="background:linear-gradient(135deg,var(--primary),var(--secondary));border-radius:10px;">
                    <i class="fas fa-save me-2"></i>Update Password
                </button>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleVis(id, btn) {
    const inp = document.getElementById(id);
    inp.type = inp.type === 'password' ? 'text' : 'password';
    btn.querySelector('i').className = inp.type === 'password' ? 'fas fa-eye' : 'fas fa-eye-slash';
}

function checkStrength(val) {
    const bar = document.getElementById('strengthBar');
    const lbl = document.getElementById('strengthLabel');
    let score = 0;
    if (val.length >= 8)  score++;
    if (/[A-Z]/.test(val)) score++;
    if (/[0-9]/.test(val)) score++;
    if (/[^A-Za-z0-9]/.test(val)) score++;
    const map = [
        {w:'0%',   cls:'bg-secondary', txt:''},
        {w:'25%',  cls:'bg-danger',    txt:'Weak'},
        {w:'50%',  cls:'bg-warning',   txt:'Fair'},
        {w:'75%',  cls:'bg-info',      txt:'Good'},
        {w:'100%', cls:'bg-success',   txt:'Strong ✓'},
    ];
    bar.style.width = map[score].w;
    bar.className = 'strength-bar ' + map[score].cls;
    lbl.textContent = map[score].txt;
}

function checkMatch() {
    const a = document.getElementById('new_pass').value;
    const b = document.getElementById('con_pass').value;
    const lbl = document.getElementById('matchLabel');
    if (!b) { lbl.textContent = ''; return; }
    lbl.textContent = a === b ? '✅ Passwords match' : '❌ Passwords do not match';
    lbl.style.color  = a === b ? 'green' : 'red';
}
</script>
</body>
</html>
