<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php"; // $conn = mysqli connection

$userlogin = $_SESSION['email'] ?? null;
$intake    = $_SESSION['department'] ?? null;

if (!$userlogin) {
  header("Location: ../index.php");
  exit;
}

// Generate PAYID server-side (UNP-YYYYMMDD-XXXX)
function generatePayId() {
  return "UNP-" . date("Ymd") . "-" . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));
}

$success = $error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $payid     = $_POST['payid'] ?? generatePayId();
  $fee_type  = trim($_POST['fee_type'] ?? '');
  $studentid = trim($_POST['studentid'] ?? '');
  $amount    = trim($_POST['amount'] ?? '');
  $intake    = trim($_POST['intake'] ?? '');
  $mobile    = trim($_POST['mobile'] ?? '');
  $year      = trim($_POST['year'] ?? '');
  $status    = trim($_POST['status'] ?? 'Paid');
  $paidday   = trim($_POST['paidday'] ?? date('Y-m-d'));
  $period    = trim($_POST['period'] ?? '');

  // Basic validation
  if ($fee_type==='' || $studentid==='' || $amount==='' || $intake==='' ||
      $mobile==='' || $year==='' || $status==='' || $paidday==='' || $period==='') {
    $error = "⚠️ Please fill in all required fields.";
  } elseif (!is_numeric($amount) || $amount <= 0) {
    $error = "⚠️ Amount must be a positive number.";
  } else {
    // Check if student exists
    $check_student = mysqli_query($conn, "SELECT studentname FROM students WHERE studentid = '$studentid'");
    if (mysqli_num_rows($check_student) == 0) {
      $error = "⚠️ Student ID not found in the system.";
    } else {
      // Insert payment
      $sql = "INSERT INTO payments 
                (payid, fee_type, studentid, amount, intake, mobile, year, status, paidday, period) 
              VALUES 
                ('$payid','$fee_type','$studentid','$amount','$intake','$mobile','$year','$status','$paidday','$period')";
      
      if (mysqli_query($conn, $sql)) {
        $success = "✅ Payment saved successfully (PAYID: {$payid}).";
        // Clear form data
        $_POST = [];
      } else {
        $error = "❌ Database error: " . mysqli_error($conn);
      }
    }
  }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Collection</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #1A8A00;
            --secondary: #17cc27;
            --light: #f8f9fa;
            --dark: #343a40;
            --success: #28a745;
            --danger: #dc3545;
            --warning: #ffc107;
        }
        
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background-color: #f5f5f5;
            color: #333;
            margin: 0;
            padding: 0;
        }
        
        .content {
            margin-left: 200px;
            padding: 20px;
        }
        
        .payment-container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            padding: 25px;
            margin-top: 20px;
        }
        
        .payment-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid var(--primary);
        }
        
        .payment-header h2 {
            color: var(--primary);
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .payment-header p {
            color: #6c757d;
            font-size: 16px;
        }
        
        .form-section {
            margin-bottom: 25px;
        }
        
        .form-section-title {
            font-size: 18px;
            font-weight: 600;
            color: var(--primary);
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 1px solid #eee;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #495057;
        }
        
        .form-control {
            border-radius: 8px;
            padding: 12px 15px;
            border: 1px solid #ced4da;
            transition: all 0.3s;
        }
        
        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(26, 138, 0, 0.25);
        }
        
        .alert {
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        
        .alert-danger {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        
        .btn-primary {
            background-color: var(--primary);
            border-color: var(--primary);
            padding: 12px 20px;
            font-weight: 600;
            border-radius: 8px;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            background-color: #136600;
            border-color: #136600;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background-color: #6c757d;
            border-color: #6c757d;
            padding: 12px 20px;
            font-weight: 600;
            border-radius: 8px;
        }
        
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
<?php include "../include/nav.php";?>

<div class="content">
    <br><br>
    <div class="payment-container">
        <div class="payment-header">
            <h2><i class="fa fa-credit-card"></i> Payment Collection</h2>
            <p>Record student payments and generate payment IDs</p>
        </div>

        <?php if ($success): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?= htmlspecialchars($success) ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <?= htmlspecialchars($error) ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        <?php endif; ?>

        <form method="post" novalidate id="paymentForm">
            <div class="form-section">
                <h4 class="form-section-title">Payment Information</h4>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="fee_type">Fee Type *</label>
                            <select id="fee_type" name="fee_type" class="form-control" required>
                                <option value="" disabled selected>Select fee type</option>
                                <option value="Tuition">General</option>

                                <option value="Tuition">Tuition</option>
                                <option value="Registration">Registration</option>
                                <option value="Library">Library</option>
                                <option value="Accommodation">Accommodation</option>
                                <option value="Examination">Examination</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="amount">Amount (ZMW) *</label>
                            <input id="amount" name="amount" type="number" step="0.01" min="0" class="form-control" required
                                   placeholder="e.g., 1500.00">
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="year">Year *</label>
                            <select id="year" name="year" class="form-control" required>
                                <option value="" disabled selected>Select year</option>
                                <?php
                                $current_year = date('Y');
                                for ($y = $current_year; $y >= $current_year - 5; $y--) {
                                    echo "<option value='$y'>$y</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="period">Semester *</label>
                            <select id="period" name="period" class="form-control" required>
                                <option value="" disabled selected>Select semester</option>
                                <option value="1">Semester 1</option>
                                <option value="2">Semester 2</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-section">
                <h4 class="form-section-title">Student Information</h4>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="studentid">Student ID *</label>
                            <input id="studentid" name="studentid" type="text" class="form-control" required
                                   placeholder="e.g., UCS/23/00124">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="intake">Intake *</label>
                            <select id="intake" name="intake" class="form-control" required>
                                <option value="" disabled selected>Select intake</option>
                                <?php
                                $query = mysqli_query($conn, "SELECT DISTINCT intake FROM intake ORDER BY intake DESC");
                                while ($row = mysqli_fetch_assoc($query)) {
                                    $intake_val = $row['intake'];
                                    echo "<option value='".htmlspecialchars($intake_val)."'>".htmlspecialchars($intake_val)."</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="mobile">Mobile Number *</label>
                            <input id="mobile" name="mobile" type="tel" class="form-control" required
                                   placeholder="+260 9XX XXX XXX">
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="form-label" for="paidday">Payment Date</label>
                            <input id="paidday" name="paidday" type="date" class="form-control" required
                                   value="<?= date('Y-m-d') ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Hidden fields -->
            <input type="hidden" name="status" value="Paid">
            <div class="form-group" hidden>
                <label class="form-label" for="payid">Payment ID</label>
                <input id="payid" name="payid" type="text" class="form-control" readonly
                       value="<?= htmlspecialchars(generatePayId()) ?>">
            </div>
            
            <div class="form-group text-center mt-4">
                <button type="submit" class="btn btn-primary btn-lg" id="submitBtn">
                    <i class="fa fa-save"></i> Save Payment
                </button>
                <button type="button" class="btn btn-secondary btn-lg ml-2" onclick="resetForm()">
                    <i class="fa fa-undo"></i> Clear Form
                </button>
            </div>
        </form>
        
        <div class="mt-4 pt-3 border-top text-center">
            <p class="text-muted">&copy; <?= date('Y') ?> Finance Office - University Payment System</p>
        </div>
    </div>
</div>

<script>
// Better form validation
document.getElementById('paymentForm').addEventListener('submit', function(e) {
    let isValid = true;
    
    // Clear previous errors
    document.querySelectorAll('.is-invalid').forEach(el => {
        el.classList.remove('is-invalid');
    });
    document.querySelectorAll('.invalid-feedback').forEach(el => {
        el.remove();
    });
    
    // Check all required fields
    const requiredFields = document.querySelectorAll('[required]');
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            field.classList.add('is-invalid');
            const error = document.createElement('div');
            error.className = 'invalid-feedback';
            error.textContent = 'This field is required';
            field.parentNode.appendChild(error);
            isValid = false;
        }
    });
    
    // Validate amount
    const amountField = document.getElementById('amount');
    if (amountField.value) {
        const amount = parseFloat(amountField.value);
        if (isNaN(amount) || amount <= 0) {
            amountField.classList.add('is-invalid');
            const error = document.createElement('div');
            error.className = 'invalid-feedback';
            error.textContent = 'Amount must be greater than 0';
            amountField.parentNode.appendChild(error);
            isValid = false;
        }
    }
    
    if (!isValid) {
        e.preventDefault();
        // Scroll to first error
        const firstError = document.querySelector('.is-invalid');
        if (firstError) {
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    } else {
        // Disable submit button to prevent double submission
        const submitBtn = document.getElementById('submitBtn');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
    }
});

// Reset form function
function resetForm() {
    if (confirm('Are you sure you want to clear all form data?')) {
        document.getElementById('paymentForm').reset();
        document.getElementById('paidday').value = '<?= date('Y-m-d') ?>';
        
        // Clear validation errors
        document.querySelectorAll('.is-invalid').forEach(el => {
            el.classList.remove('is-invalid');
        });
        document.querySelectorAll('.invalid-feedback').forEach(el => {
            el.remove();
        });
        
        // Re-enable submit button
        document.getElementById('submitBtn').disabled = false;
        document.getElementById('submitBtn').innerHTML = '<i class="fa fa-save"></i> Save Payment';
    }
}

// Auto-hide success message after 5 seconds
setTimeout(function() {
    const successAlert = document.querySelector('.alert-success');
    if (successAlert) {
        successAlert.style.transition = 'opacity 0.5s';
        successAlert.style.opacity = '0';
        setTimeout(() => {
            successAlert.style.display = 'none';
        }, 500);
    }
}, 5000);
</script>

</body>
</html>