<style>
    .hover-shadow:hover {
        transform: translateY(-3px);
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
    }
    .transition-all {
        transition: all 0.3s ease;
    }
</style>

<div class="container-fluid py-4">
    <div class="row">
        <div class="col-lg-12 mx-auto">
            <div class="card shadow-sm">
                <div class="card-header pb-0">
                    <div class="d-flex align-items-center">
                        <h4 class="mb-0">Fail Peribadi Tutor (Beta)</h4>
                    </div>
                </div>
                <div class="card-body">
                    <p>Di sini anda boleh menguruskan pautan peribadi anda.Fail Peribadi ini hanya akses kepada Tutor Milik Akaun sahaja</p>

                    <div class="mb-4">
                        <h5>Tambah Pautan Baru</h5>
                        <form id="addPersonalFileForm">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="fileUrl">URL Pautan</label>
                                        <input type="url" class="form-control" id="fileUrl" name="file_url" placeholder="Masukkan URL pautan" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="description">Penerangan</label>
                                        <input type="text" class="form-control" id="description" name="description" placeholder="Masukkan penerangan pautan" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="status">Status</label>
                                        <select class="form-control" id="status" name="status">
                                            <option value="active">Aktif</option>
                                            <option value="inactive">Tidak Aktif</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="selfDeleteOption">Mod Padam Sendiri</label>
                                        <select class="form-control" id="selfDeleteOption" name="self_delete_option">
                                            <option value="never">Tiada</option>
                                            <option value="30_days">30 Hari</option>
                                            <option value="40_days">40 Hari</option>
                                            <option value="90_days">90 Hari</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary mt-3">Tambah Pautan</button>
                        </form>
                    </div>

                    <div class="mt-5">
                        <h5>Pautan Peribadi Anda</h5>
                        <div id="personalFilesList" class="table-responsive">
                            <p>Memuatkan pautan peribadi...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Personal File Modal -->
<div class="modal fade" id="editPersonalFileModal" tabindex="-1" aria-labelledby="editPersonalFileModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editPersonalFileModalLabel">Edit Pautan Peribadi</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editPersonalFileForm">
                    <input type="hidden" id="editFileId" name="file_id">
                    <div class="form-group mb-3">
                        <label for="editFileUrl">URL Pautan</label>
                        <input type="url" class="form-control" id="editFileUrl" name="file_url" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="editDescription">Penerangan</label>
                        <input type="text" class="form-control" id="editDescription" name="description" required>
                    </div>
                    <div class="form-group mb-3">
                        <label for="editStatus">Status</label>
                        <select class="form-control" id="editStatus" name="status">
                            <option value="active">Aktif</option>
                            <option value="inactive">Tidak Aktif</option>
                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <label for="editSelfDeleteOption">Mod Padam Sendiri</label>
                        <select class="form-control" id="editSelfDeleteOption" name="self_delete_option">
                            <option value="never">Tiada</option>
                            <option value="30_days">30 Hari</option>
                            <option value="40_days">40 Hari</option>
                            <option value="90_days">90 Hari</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // Load files when the page loads
    document.addEventListener('DOMContentLoaded', loadPersonalFiles);

    document.getElementById('addPersonalFileForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        formData.append('action', 'add_personal_file');

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.json();
        })
        .then(data => {
            if (data.success) {
                Swal.fire('Berjaya', data.message, 'success');
                this.reset();
                loadPersonalFiles();
            } else {
                Swal.fire('Ralat', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire('Ralat', 'Ralat komunikasi dengan server.', 'error');
        });
    });

    document.getElementById('editPersonalFileForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        formData.append('action', 'update_personal_file');

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.json();
        })
        .then(data => {
            if (data.success) {
                Swal.fire('Berjaya', data.message, 'success');
                const modal = bootstrap.Modal.getInstance(document.getElementById('editPersonalFileModal'));
                modal.hide();
                loadPersonalFiles();
            } else {
                Swal.fire('Ralat', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire('Ralat', 'Ralat komunikasi dengan server semasa mengemaskini.', 'error');
        });
    });

    function loadPersonalFiles() {
        fetch('../api.php?action=get_personal_files')
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok');
                return response.json();
            })
            .then(data => {
                const personalFilesList = document.getElementById('personalFilesList');
                
                if (data.success && data.files && data.files.length > 0) {
                    let gridHtml = '<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3">';
                    
                    data.files.forEach(file => {
                        const deletionDate = file.deletion_date ? new Date(file.deletion_date).toLocaleDateString() : 'Tiada';
                        const deleteLabel = {
                            '30_days': '30 Hari',
                            '40_days': '40 Hari',
                            '90_days': '90 Hari',
                            'never': 'Tiada'
                        }[file.self_delete_option] || 'Tiada';

                        const statusBadge = file.status === 'active' 
                            ? '<span class="badge bg-success">Aktif</span>' 
                            : '<span class="badge bg-secondary">Tidak Aktif</span>';

                        gridHtml += `
                            <div class="col">
                                <div class="card h-100 border-0 shadow-sm hover-shadow transition-all">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <h6 class="card-title text-primary mb-0 text-truncate" title="${file.description}">
                                                ${file.description}
                                            </h6>
                                            ${statusBadge}
                                        </div>
                                        <p class="small text-muted mb-3 text-truncate">
                                            <i class="fas fa-link me-1"></i> ${file.file_url}
                                        </p>
                                        <div class="d-flex flex-wrap gap-2 mb-3">
                                            <span class="badge bg-light text-dark border">
                                                <i class="fas fa-history me-1"></i> Padam: ${deleteLabel}
                                            </span>
                                            ${file.deletion_date ? `
                                                <span class="badge bg-light text-danger border">
                                                    <i class="fas fa-calendar-times me-1"></i> ${deletionDate}
                                                </span>
                                            ` : ''}
                                        </div>
                                        <div class="d-grid gap-2">
                                            <a href="${file.file_url}" target="_blank" class="btn btn-primary btn-sm">
                                                <i class="fas fa-external-link-alt me-1"></i> Buka Pautan
                                            </a>
                                            <div class="btn-group w-100">
                                                <button class="btn btn-outline-info btn-sm edit-file-btn" 
                                                    data-id="${file.id}" 
                                                    data-url="${file.file_url}" 
                                                    data-description="${file.description}" 
                                                    data-status="${file.status}" 
                                                    data-delete-option="${file.self_delete_option}"
                                                    data-bs-toggle="modal" 
                                                    data-bs-target="#editPersonalFileModal">
                                                    <i class="fas fa-edit"></i> Edit
                                                </button>
                                                <button class="btn btn-outline-danger btn-sm delete-file-btn" data-id="${file.id}">
                                                    <i class="fas fa-trash"></i> Padam
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    gridHtml += '</div>';
                    personalFilesList.innerHTML = gridHtml;

                    // Add event listeners for edit and delete buttons
                    document.querySelectorAll('.edit-file-btn').forEach(button => {
                        button.addEventListener('click', function() {
                            document.getElementById('editFileId').value = this.dataset.id;
                            document.getElementById('editFileUrl').value = this.dataset.url;
                            document.getElementById('editDescription').value = this.dataset.description;
                            document.getElementById('editStatus').value = this.dataset.status;
                            document.getElementById('editSelfDeleteOption').value = this.dataset.deleteOption;
                        });
                    });

                    document.querySelectorAll('.delete-file-btn').forEach(button => {
                        button.addEventListener('click', function() {
                            Swal.fire({
                                title: 'Adakah anda pasti?',
                                text: "Pautan ini akan dipadamkan selama-lamanya!",
                                icon: 'warning',
                                showCancelButton: true,
                                confirmButtonColor: '#d33',
                                cancelButtonColor: '#3085d6',
                                confirmButtonText: 'Ya, padam!',
                                cancelButtonText: 'Batal'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    deletePersonalFile(this.dataset.id);
                                }
                            });
                        });
                    });

                } else {
                    personalFilesList.innerHTML = '<div class="alert alert-info">Tiada pautan peribadi ditemui.</div>';
                }
            })
            .catch(error => {
                console.error('Error loading personal files:', error);
                document.getElementById('personalFilesList').innerHTML = '<div class="alert alert-danger">Ralat memuatkan pautan peribadi. Sila cuba lagi.</div>';
            });
    }

    function deletePersonalFile(fileId) {
        const formData = new FormData();
        formData.append('action', 'delete_personal_file');
        formData.append('file_id', fileId);

        fetch('../api.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.json();
        })
        .then(data => {
            if (data.success) {
                Swal.fire('Berjaya', data.message, 'success');
                loadPersonalFiles();
            } else {
                Swal.fire('Ralat', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error deleting personal file:', error);
            Swal.fire('Ralat', 'Ralat komunikasi dengan server semasa memadam fail.', 'error');
        });
    }
</script>
