<?php
include('session_validator.php');
include('includes/db.php');

// Check if ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: view_exam_subject_marks.php');
    exit;
}

$record_id = intval($_GET['id']);

// Fetch the record to edit - FIXED: Using subjects.id instead of subjects.subject_id
$query = "SELECT 
            esm.*,
            ay.ay_bs as session_name,
            et.exam_type,
            c.class,
            s.section_name,
            sub.subject_code,
            sub.subject_name,
            sub.theory_full_marks as default_theory,
            sub.internal_full_marks as default_internal,
            sub.theory_credit_hour as default_theory_credit,
            sub.internal_credit_hour as default_internal_credit,
            sub.type as subject_type
          FROM exam_subject_marks esm
          LEFT JOIN academic_years ay ON esm.session_id = ay.year_id
          LEFT JOIN examination_type et ON esm.exam_id = et.id
          LEFT JOIN classes c ON esm.class_id = c.class_id
          LEFT JOIN sections s ON esm.section_id = s.section_id
          LEFT JOIN subjects sub ON esm.subject_id = sub.id  -- FIXED: Changed sub.subject_id to sub.id
          WHERE esm.id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $record_id);
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_assoc();

if (!$record) {
    header('Location: view_exam_subject_marks.php');
    exit;
}
$stmt->close();

// Handle form submission for update
$alert = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
    $theory_marks = floatval($_POST['full_marks_theory']);
    $internal_marks = floatval($_POST['full_marks_internal']);
    $theory_credit = floatval($_POST['theory_credit_hour']);
    $internal_credit = floatval($_POST['internal_credit_hour']);
    $remarks = $conn->real_escape_string($_POST['remarks']);
    $user_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 0;
    
    // Validate
    if ($theory_marks < 0 || $theory_marks > 1000 || 
        $internal_marks < 0 || $internal_marks > 1000 ||
        $theory_credit < 0 || $theory_credit > 10 ||
        $internal_credit < 0 || $internal_credit > 10) {
        $alert = "validation_error";
    } else {
        $update_query = "UPDATE exam_subject_marks SET 
                        full_marks_theory = ?,
                        full_marks_internal = ?,
                        theory_credit_hour = ?,
                        internal_credit_hour = ?,
                        remarks = ?,
                        updated_by = ?
                        WHERE id = ?";
        
        $update_stmt = $conn->prepare($update_query);
        $update_stmt->bind_param("ddddssi", $theory_marks, $internal_marks, $theory_credit, $internal_credit, $remarks, $user_id, $record_id);
        
        if ($update_stmt->execute()) {
            $alert = "update_success";
            // Refresh record data
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $record_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $record = $result->fetch_assoc();
            $stmt->close();
        } else {
            $alert = "update_error";
        }
        $update_stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Subject Marks</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <link rel="stylesheet" href="css/main.css">
    <style>
        .info-card {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid #007bff;
        }
        
        .info-label {
            font-weight: 600;
            color: #495057;
        }
        
        .info-value {
            color: #212529;
        }
        
        .default-value {
            color: #6c757d;
            font-size: 0.9rem;
        }
    </style>
</head>

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>
               
                <div class="main-page">
                    <div class="container-fluid">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title"><i class="fa fa-edit"></i> Edit Subject Marks</h2>
                            </div>
                            <div class="col-md-6 text-right">
                                <a href="view_exam_subject_marks.php" class="btn btn-secondary">
                                    <i class="fa fa-arrow-left"></i> Back to List
                                </a>
                            </div>
                        </div>

                        <div class="row breadcrumb-div">
                            <div class="col-md-12">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li><a href="view_exam_subject_marks.php">View Subject Marks</a></li>
                                    <li class="active">Edit Marks</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5><i class="fa fa-pencil"></i> Edit Subject Marks</h5>
                                        </div>
                                    </div>
                                    
                                    <div class="panel-body">
                                        <!-- Display Record Info -->
                                        <div class="info-card">
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <p class="info-label">Session:</p>
                                                    <p class="info-value"><?= htmlspecialchars($record['session_name']) ?></p>
                                                </div>
                                                <div class="col-md-3">
                                                    <p class="info-label">Exam:</p>
                                                    <p class="info-value"><?= htmlspecialchars($record['exam_type']) ?></p>
                                                </div>
                                                <div class="col-md-3">
                                                    <p class="info-label">Class-Section:</p>
                                                    <p class="info-value"><?= htmlspecialchars($record['class']) ?> - <?= htmlspecialchars($record['section_name']) ?></p>
                                                </div>
                                                <div class="col-md-3">
                                                    <p class="info-label">Subject:</p>
                                                    <p class="info-value">
                                                        <?= htmlspecialchars($record['subject_name']) ?><br>
                                                        <small class="text-muted"><?= htmlspecialchars($record['subject_code']) ?></small>
                                                    </p>
                                                </div>
                                            </div>
                                            <div class="row mt-3">
                                                <div class="col-md-4">
                                                    <p class="info-label">Created At:</p>
                                                    <p class="info-value">
                                                        <?= !empty($record['created_at']) ? date('d-M-Y H:i:s', strtotime($record['created_at'])) : 'N/A' ?>
                                                    </p>
                                                </div>
                                                <div class="col-md-4">
                                                    <p class="info-label">Last Updated:</p>
                                                    <p class="info-value">
                                                        <?= !empty($record['updated_at']) ? date('d-M-Y H:i:s', strtotime($record['updated_at'])) : 'Not updated yet' ?>
                                                    </p>
                                                </div>
                                                <div class="col-md-4">
                                                    <p class="info-label">Subject Type:</p>
                                                    <p class="info-value">
                                                        <?= ucfirst(htmlspecialchars($record['subject_type'])) ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Edit Form -->
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Theory Full Marks *</label>
                                                        <input type="number" step="0.01" min="0" max="1000" 
                                                               name="full_marks_theory" class="form-control" 
                                                               value="<?= htmlspecialchars($record['full_marks_theory']) ?>" required>
                                                        <small class="form-text text-muted default-value">
                                                            Default: <?= htmlspecialchars($record['default_theory']) ?>
                                                        </small>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Internal Full Marks *</label>
                                                        <input type="number" step="0.01" min="0" max="1000" 
                                                               name="full_marks_internal" class="form-control" 
                                                               value="<?= htmlspecialchars($record['full_marks_internal']) ?>" required>
                                                        <small class="form-text text-muted default-value">
                                                            Default: <?= htmlspecialchars($record['default_internal']) ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Theory Credit Hour *</label>
                                                        <input type="number" step="0.01" min="0" max="10" 
                                                               name="theory_credit_hour" class="form-control" 
                                                               value="<?= htmlspecialchars($record['theory_credit_hour']) ?>" required>
                                                        <small class="form-text text-muted default-value">
                                                            Default: <?= htmlspecialchars($record['default_theory_credit']) ?>
                                                        </small>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label>Internal Credit Hour *</label>
                                                        <input type="number" step="0.01" min="0" max="10" 
                                                               name="internal_credit_hour" class="form-control" 
                                                               value="<?= htmlspecialchars($record['internal_credit_hour']) ?>" required>
                                                        <small class="form-text text-muted default-value">
                                                            Default: <?= htmlspecialchars($record['default_internal_credit']) ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label>Remarks</label>
                                                <textarea name="remarks" class="form-control" rows="3"><?= htmlspecialchars($record['remarks']) ?></textarea>
                                            </div>
                                            
                                            <div class="text-right">
                                                <button type="submit" name="update" class="btn btn-primary">
                                                    <i class="fa fa-save"></i> Update Marks
                                                </button>
                                                <a href="view_exam_subject_marks.php" class="btn btn-secondary">
                                                    <i class="fa fa-times"></i> Cancel
                                                </a>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="js/datatables/datatables.min.js"></script>
    <script src="js/main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        $(document).ready(function() {
            // Form validation
            $('form').submit(function(e) {
                const theoryMarks = parseFloat($('input[name="full_marks_theory"]').val());
                const internalMarks = parseFloat($('input[name="full_marks_internal"]').val());
                const theoryCredit = parseFloat($('input[name="theory_credit_hour"]').val());
                const internalCredit = parseFloat($('input[name="internal_credit_hour"]').val());
                
                let errors = [];
                
                if (theoryMarks < 0 || theoryMarks > 1000) {
                    errors.push("Theory marks must be between 0 and 1000");
                }
                if (internalMarks < 0 || internalMarks > 1000) {
                    errors.push("Internal marks must be between 0 and 1000");
                }
                if (theoryCredit < 0 || theoryCredit > 10) {
                    errors.push("Theory credit hour must be between 0 and 10");
                }
                if (internalCredit < 0 || internalCredit > 10) {
                    errors.push("Internal credit hour must be between 0 and 10");
                }
                
                if (errors.length > 0) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        html: errors.join('<br>'),
                        confirmButtonText: 'OK'
                    });
                }
            });
        });

        <?php if ($alert === "update_success"): ?>
            Swal.fire({
                icon: 'success',
                title: 'Updated!',
                text: 'Subject marks have been updated successfully.',
                timer: 3000,
                showConfirmButton: false
            });
        <?php elseif ($alert === "update_error"): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Failed to update marks. Please try again.',
                confirmButtonText: 'OK'
            });
        <?php elseif ($alert === "validation_error"): ?>
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please check your input values. Marks must be between 0-1000 and credits between 0-10.',
                confirmButtonText: 'OK'
            });
        <?php endif; ?>
    </script>

</body>

</html>