????????????????????
??????????????????
ÿØÿà
 JFIF      ÿÛ C      


!"$"$ÿÛ C    
ÿÂ p 
" ÿÄ     
         ÿÄ             ÿÚ 
   ÕÔË®

(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

adadasdasdasasdasdas


.....................................................................................................................................????????????????????
??????????????????
ÿØÿà
 JFIF      ÿÛ C      


!"$"$ÿÛ C    
ÿÂ p 
" ÿÄ     
         ÿÄ             ÿÚ 
   ÕÔË®

(%	aA*‚XYD¡(J„¡E¢RE,P€XYae )(E¤²€B¤R¥	BQ¤¢ X«)X…€¤   @  

adadasdasdasasdasdas


.....................................................................................................................................<?php
include('session.php');
include 'connection.php';
 
/// Fetch existing record
if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $result = mysqli_query($conn, "SELECT * FROM certificates WHERE id=$id");
    $data = mysqli_fetch_assoc($result);
} else {
    die("Invalid request!");
}

// Handle update form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $student_name = $_POST['student_name'];
    $father_name = $_POST['father_name'];
    $registration_no = $_POST['registration_no'];
    $certificate_no = $_POST['certificate_no'];
    $course_name = $_POST['course_name'];
    $session = $_POST['session'];
    $duration = $_POST['duration'];
    $grade = $_POST['grade'];
    $exam_held = $_POST['exam_held'];
    $issue_date = $_POST['issue_date'];

    // Check if a new image is uploaded
    $target_dir = "uploads/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    
    if (!empty($_FILES["certificate_image"]["name"])) {
        $file_name = basename($_FILES["certificate_image"]["name"]);
        $target_file = $target_dir . time() . "_" . $file_name;
        move_uploaded_file($_FILES["certificate_image"]["tmp_name"], $target_file);

        // Delete old image if exists
        if (!empty($data['certificate_image']) && file_exists($data['certificate_image'])) {
            unlink($data['certificate_image']);
        }
    } else {
        $target_file = $data['certificate_image'];
    }

    // Handle student photo upload
    if (!empty($_FILES["student_photo"]["name"])) {
        $student_photo_name = basename($_FILES["student_photo"]["name"]);
        $student_photo_target = $target_dir . time() . "_student_" . $student_photo_name;
        move_uploaded_file($_FILES["student_photo"]["tmp_name"], $student_photo_target);

        // Delete old student photo if it exists
        if (!empty($data['student_photo']) && file_exists($data['student_photo'])) {
            unlink($data['student_photo']);
        }
    } else {
        $student_photo_target = $data['student_photo'];
    }

    // Update record
    $sql = "UPDATE certificates SET 
                student_name='$student_name', 
                father_name='$father_name', 
                registration_no='$registration_no', 
                certificate_no='$certificate_no', 
                course_name='$course_name', 
                session='$session', 
                duration='$duration',
                grade='$grade',
                exam_held='$exam_held',
                issue_date='$issue_date', 
                certificate_image='$target_file',
                student_photo='$student_photo_target'
            WHERE id=$id";

    if (mysqli_query($conn, $sql)) {
        echo "<script>alert('Certificate Updated Successfully!'); window.location='certificate_upload.php';</script>";
    } else {
        echo "<script>alert('Error updating record!');</script>";
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Fee Report |Xcel Training Institute</title>
    <!-- Favicon icon -->
    <link rel="icon" type="image/png" href="../images/logo-wide.png">
    <!-- Base Styling  -->
    <link rel="stylesheet" href="assets/main/css/fonts.css">
    <link rel="stylesheet" href="assets/main/css/style.css">
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    <style>
    body { font-family: Arial, sans-serif; background: #f4f4f4; padding: 20px; }
    .form-container { background: #fff; padding: 20px; border-radius: 10px; max-width: 800px; margin: auto; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
    input, select { width: 100%; padding: 8px; margin: 6px 0; border: 1px solid #ccc; border-radius: 5px; }
    button { background: #28a745; color: #fff; border: none; padding: 10px 15px; border-radius: 5px; cursor: pointer; }
    button:hover { background: #218838; }
    img { width: 120px; height: auto; margin-top: 10px; border-radius: 5px; }
</style>
</head>

<body>
    <div id="main-wrapper" class="show">

        <?php include "sidebar.php"; ?>
        <?php include "header.php"; ?>

        <div class="content-body">
            <div class="warper container-fluid">
                <div class="new-patients main_container">
                    
                    <div class="row">
                       <div class="form-container">
    <h2>Edit Certificate</h2>
    <form method="POST" enctype="multipart/form-data">
        <label>Student Name:</label>
        <input type="text" name="student_name" value="<?= htmlspecialchars($data['student_name']) ?>" required>

        <label>Father's Name:</label>
        <input type="text" name="father_name" value="<?= htmlspecialchars($data['father_name']) ?>" required>

        <label>Registration No:</label>
        <input type="text" name="registration_no" value="<?= htmlspecialchars($data['registration_no']) ?>" required>

        <label>Certificate No:</label>
        <input type="text" name="certificate_no" value="<?= htmlspecialchars($data['certificate_no']) ?>" required>

        <label>Course Name:</label>
        <input type="text" name="course_name" value="<?= htmlspecialchars($data['course_name']) ?>" required>

        <label>Session:</label>
        <input type="text" name="session" value="<?= htmlspecialchars($data['session']) ?>" required>

        <label>Duration:</label>
        <input type="text" name="duration" value="<?= htmlspecialchars($data['duration'] ?? '') ?>" required>

        <label>Grade:</label>
        <input type="text" name="grade" value="<?= htmlspecialchars($data['grade'] ?? '') ?>" required>

        <label>Exam Held:</label>
        <input type="text" name="exam_held" value="<?= htmlspecialchars($data['exam_held'] ?? '') ?>" required>

        <label>Certificate Issue Date:</label>
        <input type="date" name="issue_date" value="<?= $data['issue_date'] ?>" required>

        <label>Current Certificate Image:</label><br>
        <img src="<?= $data['certificate_image'] ?>" alt="Certificate Image"><br><br>

        <label>Current Student Photo:</label><br>
        <img src="<?= $data['student_photo'] ?>" alt="Student Photo"><br><br>

        <label>Upload New Student Photo (Optional):</label>
        <input type="file" name="student_photo" accept="image/*">

        <label>Upload New Image (Optional):</label>
        <input type="file" name="certificate_image" accept="image/*">

        <button type="submit">Update</button>
        <a href="certificate_upload.php" style="margin-left:10px; background:#6c757d; color:#fff; padding:10px 15px; border-radius:5px; text-decoration:none;">Cancel</a>
    </form>
</div>

<script>
function validateForm() {
    const certNo = document.getElementById("certificate_no").value.trim();
    if (certNo === "") {
        alert("Certificate Number cannot be empty!");
        return false;
    }
    return true;
}
</script>
                    </div>
                    
                </div>
            </div>
        </div>
        <!-- End section content -->

        <?php include('footer.php'); ?>
    </div>

    <!-- Student Details Modal -->
    <div id="studentDetailsModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2 id="modalTitle">Student Details</h2>
            <div id="modalBody">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>

    <script>
    // Modal functionality
    var modal = document.getElementById("studentDetailsModal");
    var span = document.getElementsByClassName("close")[0];

    span.onclick = function() {
        modal.style.display = "none";
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

    // Toggle fee status via AJAX (Approved <-> Pending)
    function toggleFeeStatus(feeId, btnEl) {
        if (!feeId) return;
        var $btn = $(btnEl);
        var current = ($btn.text() || '').trim().toLowerCase();
        var nextStatus = current === 'approved' ? 'Pending' : 'Approved';
        var savingLabel = nextStatus === 'Approved' ? 'Approving...' : 'Setting Pending...';
        $btn.prop('disabled', true).text(savingLabel);
        $.post('update_fee_status.php', { id: feeId, status: nextStatus }, function(resp) {
            try { resp = (typeof resp === 'object') ? resp : JSON.parse(resp); } catch(e) { resp = { success:false, message: e.message }; }
            if (resp.success) {
                if (nextStatus === 'Approved') {
                    $btn.removeClass('btn-warning').addClass('btn-success').text('Approved');
                } else {
                    $btn.removeClass('btn-success').addClass('btn-warning').text('Pending');
                }
            } else {
                alert('Failed to update: ' + (resp.message || 'Unknown error'));
                // Revert to opposite label if failed
                if (current === 'approved') {
                    $btn.removeClass('btn-success').addClass('btn-warning').text('Pending');
                } else {
                    $btn.removeClass('btn-warning').addClass('btn-success').text('Approved');
                }
            }
            $btn.prop('disabled', false);
        }).fail(function(){
            alert('Request failed');
            // Revert UI to the other state label
            if (current === 'approved') {
                $btn.removeClass('btn-success').addClass('btn-warning').text('Pending');
            } else {
                $btn.removeClass('btn-warning').addClass('btn-success').text('Approved');
            }
            $btn.prop('disabled', false);
        });
    }

    // Function to show student details
    function showStudentDetails(admission_no) {
        modal.style.display = "block";
        
        // Show loading
        document.getElementById("modalBody").innerHTML = '<div style="text-align: center; padding: 20px;"><i class="fas fa-spinner fa-spin"></i> Loading...</div>';
        
        // Fetch student details via AJAX
        $.post("get_student_details.php", {admission_no: admission_no}, function(response) {
            console.log('Raw response:', response);
            console.log('Response type:', typeof response);
            
            var data;
            
            // Check if response is already parsed by jQuery
            if (typeof response === 'object') {
                data = response;
            } else {
                try {
                    data = JSON.parse(response);
                } catch (e) {
                    console.error('JSON Parse Error:', e);
                    document.getElementById("modalBody").innerHTML = '<div class="alert alert-danger">Error parsing response: ' + e.message + '</div>';
                    return;
                }
            }
            
            if (data.success) {
                displayStudentDetails(data.student, data.account, data.payments);
            } else {
                document.getElementById("modalBody").innerHTML = '<div class="alert alert-danger">' + data.message + '</div>';
            }
        }).fail(function(xhr, status, error) {
            console.error('AJAX Error:', status, error);
            document.getElementById("modalBody").innerHTML = '<div class="alert alert-danger">Failed to load student details: ' + error + '</div>';
        });
    }

    // Function to display student details in modal
    function displayStudentDetails(student, account, payments) {
        var html = '';
        
        // Student Info
        html += '<div class="student-info">';
        html += '<h4>Student Information</h4>';
        html += '<div class="row">';
        html += '<div class="col-md-6"><strong>Name:</strong> ' + student.student_name + '</div>';
        html += '<div class="col-md-6"><strong>Father\'s Name:</strong> ' + student.fathers_name + '</div>';
        html += '<div class="col-md-6"><strong>Admission No:</strong> ' + student.admission_no + '</div>';
        html += '<div class="col-md-6"><strong>Mobile:</strong> ' + student.mobile_no + '</div>';
        html += '<div class="col-md-6"><strong>Course:</strong> ' + student.course_name + '</div>';
        html += '<div class="col-md-6"><strong>Course Fee:</strong> ₹' + parseFloat(student.total_fee).toFixed(2) + '</div>';
        html += '</div>';
        html += '</div>';
        
        // Account Summary
        html += '<div class="summary-box">';
        html += '<h4>Account Summary</h4>';
        html += '<div class="row">';
        html += '<div class="col-md-3"><strong>Total Fees:</strong><br>₹' + parseFloat(account.total_fees || student.total_fee).toFixed(2) + '</div>';
        html += '<div class="col-md-3"><strong>Due Amount:</strong><br>₹' + parseFloat(account.due_amount || student.total_fee).toFixed(2) + '</div>';
        html += '<div class="col-md-3"><strong>Paid Amount:</strong><br>₹' + parseFloat(account.paid_amount || 0).toFixed(2) + '</div>';
        html += '<div class="col-md-3"><strong>Total Received:</strong><br>₹' + parseFloat(account.received_amount || 0).toFixed(2) + '</div>';
        html += '</div>';
        html += '</div>';
        
        // Payment History
        html += '<div class="payment-history">';
        html += '<h4>Payment History</h4>';
        
        if (payments && payments.length > 0) {
            payments.forEach(function(payment, index) {
                html += '<div class="payment-row">';
                html += '<div class="row">';
                html += '<div class="col-md-2"><strong>Payment #' + (index + 1) + '</strong></div>';
                html += '<div class="col-md-2">₹' + parseFloat(payment.received_amount).toFixed(2) + '</div>';
                html += '<div class="col-md-2">' + payment.payment_date + '</div>';
                html += '<div class="col-md-2">MR: ' + payment.mr_no + '</div>';
                html += '<div class="col-md-2">' + (payment.transaction_id || '-') + '</div>';
                html += '<div class="col-md-2">' + (payment.bank_upi || '-') + '</div>';
                html += '</div>';
                html += '</div>';
            });
        } else {
            html += '<div class="payment-row">No payment history found</div>';
        }
        
        html += '</div>';
        
        document.getElementById("modalBody").innerHTML = html;
    }
    </script>

    <!-- Include other scripts -->
   <script src="assets/plugins/popper/popper.min.js"></script>

    <!-- Bootstrap -->
    <script src="assets/plugins/bootstrap/js/bootstrap.js"></script>

    <!-- Moment -->
    <script src="assets/plugins/moment/moment.min.js"></script>

    <!-- Date Range Picker -->
    <script src="assets/plugins/daterangepicker/daterangepicker.min.js"></script>

    <!-- Datatable -->
    <script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
    <script src="assets/js/init-tdatatable.js"></script>

    <!-- DataTables Buttons (CDN) for export) -->
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

    <script>
    // Initialize export buttons on fee report table
    (function(){
      if (!jQuery.fn.dataTable) return;
      if (!jQuery.fn.dataTable.Buttons) return;
      var sel = '#feeReportTable';
      if (!jQuery(sel).length) return;
      try { jQuery(sel).DataTable().destroy(); } catch(e) {}
      jQuery(sel).DataTable({
        order: [[0,'desc']],
        dom: 'Bfrtip',
        buttons: [
          {extend: 'copy', title: 'Fee Report'},
          {extend: 'csv', title: 'Fee Report'},
          {extend: 'excel', title: 'Fee Report'},
          {extend: 'pdf', title: 'Fee Report'},
          {extend: 'print', title: 'Fee Report'}
        ]
      });
    })();
    </script>

    <!-- Chart js -->
    <script src="assets/plugins/chart/chart/Chart.min.js"></script>
    <script src="assets/js/charts-custom.js"></script>

    <!-- Main Custom JQuery -->
    <script src="assets/js/toggleFullScreen.js"></script>
    <script src="assets/js/main.js"></script>
</body>
</html>