<?php
include 'includes/db.php';
include 'includes/header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$message = "";

// Handle Record Deletion
if (isset($_GET['delete'])) {
    $record_id = $_GET['delete'];
    $conn->query("DELETE FROM academic_records WHERE id = $record_id AND user_id = $user_id");
    header("Location: application_academic.php");
    exit();
}

// Handle Record Addition
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $degree_title = $conn->real_escape_string($_POST['degree_title']);
    $institute = $conn->real_escape_string($_POST['institute']);
    $passing_year = $conn->real_escape_string($_POST['passing_year']);
    $obtained_marks = $conn->real_escape_string($_POST['obtained_marks']);
    $total_marks = $conn->real_escape_string($_POST['total_marks']);

    $sql = "INSERT INTO academic_records (user_id, degree_title, institute, passing_year, obtained_marks, total_marks) 
            VALUES ($user_id, '$degree_title', '$institute', '$passing_year', '$obtained_marks', '$total_marks')";
    
    if ($conn->query($sql) === TRUE) {
        $message = "Record added successfully!";
    } else {
        $message = "Error adding record: " . $conn->error;
    }
}

// Fetch existing records
$sql_records = "SELECT * FROM academic_records WHERE user_id = $user_id ORDER BY passing_year DESC";
$result_records = $conn->query($sql_records);
?>

<div class="dashboard-container">
    <div class="sidebar">
        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-tachometer-alt" style="margin-right: 10px;"></i> Dashboard</a></li>
            <li><a href="application.php" class="active"><i class="fas fa-edit" style="margin-right: 10px;"></i> New Application</a></li>
            <li><a href="profile.php"><i class="fas fa-user" style="margin-right: 10px;"></i> My Profile</a></li>
            <li><a href="logout.php"><i class="fas fa-sign-out-alt" style="margin-right: 10px;"></i> Logout</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Step 2: Academic Records</h3>
            </div>
            
            <div style="margin-bottom: 20px;">
                <span class="badge badge-success">Step 1: Personal</span>
                <span class="badge badge-success">Step 2: Academic</span>
                <span class="badge badge-warning">Step 3: Documents</span>
                <span class="badge badge-warning">Step 4: Review</span>
            </div>

            <?php if($message): ?>
                <div class="alert alert-success"><?php echo $message; ?></div>
            <?php endif; ?>

            <!-- Add New Record Form -->
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 30px; border: 1px solid #ddd;">
                <h4 style="margin-top: 0; margin-bottom: 20px;">Add Academic Record</h4>
                <form method="POST" action="">
                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div class="form-group" style="flex: 1;">
                            <label>Degree Title</label>
                            <select name="degree_title" class="form-control" required>
                                <option value="">-- Select --</option>
                                <option value="Matriculation">Matriculation / O-Level</option>
                                <option value="Intermediate">Intermediate / A-Level</option>
                                <option value="Bachelor">Bachelor (14 Years)</option>
                                <option value="Bachelor Hons">Bachelor (16 Years)</option>
                                <option value="Master">Master (16 Years)</option>
                                <option value="MS/MPhil">MS / MPhil</option>
                            </select>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Institute / Board</label>
                            <input type="text" name="institute" class="form-control" required>
                        </div>
                    </div>

                    <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                        <div class="form-group" style="flex: 1;">
                            <label>Passing Year</label>
                            <input type="number" name="passing_year" class="form-control" min="1990" max="2025" required>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Obtained Marks / CGPA</label>
                            <input type="text" name="obtained_marks" id="obtained_marks" class="form-control" required>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Total Marks / CGPA</label>
                            <input type="text" name="total_marks" id="total_marks" class="form-control" required>
                        </div>
                        <div class="form-group" style="flex: 1;">
                            <label>Percentage</label>
                            <input type="text" id="percentage" class="form-control" readonly style="background: #f5f5f5;">
                        </div>
                    </div>
                    
                    <button type="button" onclick="calculatePercentage()" class="btn-outline" style="padding: 8px 20px; margin-right: 10px;"><i class="fas fa-calculator"></i> Calculate Percentage</button>
                    <button type="submit" class="btn-primary" style="padding: 8px 20px;"><i class="fas fa-plus"></i> Add Record</button>
                </form>
            </div>

            <!-- Existing Records List -->
            <h4 style="margin-bottom: 15px;">Added Records</h4>
            <table>
                <thead>
                    <tr>
                        <th>Degree</th>
                        <th>Institute</th>
                        <th>Year</th>
                        <th>Marks</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result_records->num_rows > 0): ?>
                        <?php while($row = $result_records->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $row['degree_title']; ?></td>
                            <td><?php echo $row['institute']; ?></td>
                            <td><?php echo $row['passing_year']; ?></td>
                            <td><?php echo $row['obtained_marks']; ?> / <?php echo $row['total_marks']; ?>
                            <?php 
                            if(is_numeric($row['obtained_marks']) && is_numeric($row['total_marks']) && $row['total_marks'] > 0) {
                                $percentage = ($row['obtained_marks'] / $row['total_marks']) * 100;
                                echo " (" . number_format($percentage, 2) . "%)";
                            }
                            ?>
                            </td>
                            <td>
                                <a href="application_academic.php?delete=<?php echo $row['id']; ?>" style="color: red;" onclick="return confirm('Are you sure?')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" class="text-center">No academic records added yet.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <div style="text-align: right; margin-top: 30px;">
                <a href="application.php" class="btn-outline" style="padding: 10px 20px; margin-right: 10px; text-decoration: none;">Back</a>
                <?php if ($result_records->num_rows > 0): ?>
                    <a href="application_documents.php" class="btn-primary" style="padding: 10px 30px; text-decoration: none;">Next: Upload Documents <i class="fas fa-arrow-right"></i></a>
                <?php else: ?>
                    <button class="btn-primary" style="padding: 10px 30px; opacity: 0.5; cursor: not-allowed;" disabled>Next: Upload Documents <i class="fas fa-arrow-right"></i></button>
                    <p style="color: red; font-size: 0.9rem; margin-top: 5px;">Please add at least one academic record to proceed.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
