<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";
$userlogin = $_SESSION['email'];
$userrole = $_SESSION['role'];

if (!isset($_SESSION['email']) || $userrole != "Finance") {
    header("location:../index.php");
    exit();
}

// Get payment ID and student ID from URL
$payment_id = isset($_GET['id']) ? mysqli_real_escape_string($conn, $_GET['id']) : '';
$studentid = isset($_GET['studentid']) ? mysqli_real_escape_string($conn, $_GET['studentid']) : '';

if (empty($payment_id) || empty($studentid)) {
    header("location: student_balance_report.php");
    exit();
}

// Get payment details
$payment_query = mysqli_query($conn, "SELECT * FROM payments WHERE id = '$payment_id'");
if (!$payment_query || mysqli_num_rows($payment_query) == 0) {
    header("location: payment_record.php?studentid=$studentid&msg=error");
    exit();
}

$payment = mysqli_fetch_assoc($payment_query);

// Get student details
$student_query = mysqli_query($conn, "SELECT * FROM students WHERE studentid = '$studentid'");
$student = mysqli_fetch_assoc($student_query);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $year = mysqli_real_escape_string($conn, $_POST['year']);
    $period = mysqli_real_escape_string($conn, $_POST['period']);
    $payid = mysqli_real_escape_string($conn, $_POST['payid']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $payment_date = mysqli_real_escape_string($conn, $_POST['payment_date']);
    
    // Determine the amount field name in the database
    $amount_field = isset($payment['amount']) ? 'amount' : 
                   (isset($payment['payment_amount']) ? 'payment_amount' : 'amount_paid');
    
    $update_query = mysqli_query($conn, "UPDATE payments SET 
        $amount_field = '$amount',
        year = '$year',
        period = '$period',
        payid = '$payid',
        status = '$status',
        payment_date = '$payment_date'
        WHERE id = '$payment_id'");
    
    if ($update_query) {
        header("location: payment_record.php?studentid=$studentid&msg=updated");
        exit();
    } else {
        $error = "Error updating payment: " . mysqli_error($conn);
    }
}

// Determine the amount field name and value
$amount_field = isset($payment['amount']) ? 'amount' : 
               (isset($payment['payment_amount']) ? 'payment_amount' : 'amount_paid');
$current_amount = $payment[$amount_field] ?? 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Payment - <?php echo $student['studentname']; ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background: #f8f9fa;
        }
        .content {
            margin-left: 200px;
            padding: 20px;
        }
        .form-container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .back-btn {
            background: #6c757d;
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 6px;
            text-decoration: none;
            display: inline-block;
            margin-bottom: 20px;
        }
        .back-btn:hover {
            background: #5a6268;
            color: white;
            text-decoration: none;
        }
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }
        }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>

<div class="content">
    <!-- Back Button -->
    <a href="payment_record.php?studentid=<?php echo $studentid; ?>" class="back-btn">
        <i class="fas fa-arrow-left me-2"></i> Back to Payment Record
    </a>

    <div class="form-container">
        <h2 class="mb-4"><i class="fas fa-edit me-2"></i> Edit Payment</h2>
        
        <!-- Student Info -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">Student Information</h5>
                <p class="mb-1"><strong>Name:</strong> <?php echo htmlspecialchars($student['studentname']); ?></p>
                <p class="mb-1"><strong>Student ID:</strong> <?php echo $student['studentid']; ?></p>
                <p class="mb-0"><strong>Program:</strong> <?php echo htmlspecialchars($student['program']); ?></p>
            </div>
        </div>

        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="payid" class="form-label">Receipt Number *</label>
                    <input type="text" class="form-control" id="payid" name="payid" 
                           value="<?php echo htmlspecialchars($payment['payid']); ?>" required>
                </div>
                
                <div class="col-md-6 mb-3">
                    <label for="amount" class="form-label">Amount *</label>
                    <div class="input-group">
                        <span class="input-group-text">K</span>
                        <input type="number" class="form-control" id="amount" name="amount" 
                               step="0.01" min="0" value="<?php echo $current_amount; ?>" required>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4 mb-3">
                    <label for="year" class="form-label">Year *</label>
                    <select class="form-control" id="year" name="year" required>
                        <option value="">Select Year</option>
                        <?php
                        $current_year = date('Y');
                        for ($year = $current_year; $year >= 2020; $year--): ?>
                            <option value="<?php echo $year; ?>" 
                                <?php echo ($payment['year'] == $year) ? 'selected' : ''; ?>>
                                <?php echo $year; ?>
                            </option>
                        <?php endfor; ?>
                    </select>
                </div>
                
                <div class="col-md-4 mb-3">
                    <label for="period" class="form-label">Semester *</label>
                    <select class="form-control" id="period" name="period" required>
                        <option value="">Select Semester</option>
                        <option value="Semester 1" <?php echo ($payment['period'] == 'Semester 1') ? 'selected' : ''; ?>>Semester 1</option>
                        <option value="Semester 2" <?php echo ($payment['period'] == 'Semester 2') ? 'selected' : ''; ?>>Semester 2</option>
                        <option value="Semester 3" <?php echo ($payment['period'] == 'Semester 3') ? 'selected' : ''; ?>>Semester 3</option>
                        <option value="Annual" <?php echo ($payment['period'] == 'Annual') ? 'selected' : ''; ?>>Annual</option>
                    </select>
                </div>
                
                <div class="col-md-4 mb-3">
                    <label for="payment_date" class="form-label">Payment Date *</label>
                    <input type="date" class="form-control" id="payment_date" name="payment_date" 
                           value="<?php echo isset($payment['payment_date']) ? date('Y-m-d', strtotime($payment['payment_date'])) : date('Y-m-d'); ?>" required>
                </div>
            </div>

            <div class="mb-3">
                <label for="status" class="form-label">Notes/Status</label>
                <textarea class="form-control" id="status" name="status" rows="3"><?php echo htmlspecialchars($payment['status']); ?></textarea>
            </div>

            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <a href="payment_record.php?studentid=<?php echo $studentid; ?>" class="btn btn-secondary me-md-2">
                    <i class="fas fa-times me-2"></i> Cancel
                </a>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save me-2"></i> Update Payment
                </button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>