@extends('layouts.app')

@section('content')
<div class="container py-5">
    <h1>Change Password</h1>
    <div id="alert" class="alert d-none" role="alert"></div>
    <form id="changePasswordForm">
        <div class="mb-3">
            <label class="form-label">New Password</label>
            <input type="password" class="form-control" id="password" name="password" required>
        </div>
        <div class="mb-3">
            <label class="form-label">Confirm Password</label>
            <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" required>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    document.getElementById('changePasswordForm').addEventListener('submit', async function (e) {
        e.preventDefault();

        const password = document.getElementById('password').value.trim();
        const passwordConfirmation = document.getElementById('password_confirmation').value.trim();
        const adminUuid = localStorage.getItem('admin_uuid');
        const alertBox = document.getElementById('alert');

        if (password !== passwordConfirmation) {
            alertBox.classList.remove('d-none', 'alert-success');
            alertBox.classList.add('alert-danger');
            alertBox.textContent = 'Passwords do not match';
            return;
        }

        const apiBaseUrl = 'http://localhost:8080/api';

        try {
            const response = await axios.post(${apiBaseUrl}/cms/login_changePassword, {
                admin_uuid: adminUuid,
                password: password,
                password_confirmation: passwordConfirmation,
            });

            if (!response.data.success) {
                throw new Error(response.data.message || 'Password change failed');
            }

            alertBox.classList.remove('d-none', 'alert-danger');
            alertBox.classList.add('alert-success');
            alertBox.textContent = 'Password changed successfully! Redirecting...';

            localStorage.setItem('authToken', response.data.data.token);
            localStorage.removeItem('admin_uuid');

            setTimeout(() => {
                window.location.href = '{{ url("/my-profile") }}';
            }, 1000);
        } catch (error) {
            alertBox.classList.remove('d-none', 'alert-success');
            alertBox.classList.add('alert-danger');
            alertBox.textContent = error.response?.data?.message || error.message || 'Password change failed.';
        }
    });
</script>
@endsection