<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

$error = '';
$success = '';

// Get students for dropdown
$stmt = $pdo->query("SELECT s.id, s.first_name, s.last_name, u.email FROM students s JOIN users u ON s.id = u.id ORDER BY s.last_name, s.first_name");
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get payment types for dropdown
$stmt = $pdo->query("SELECT * FROM payment_types WHERE is_active = 1 ORDER BY name");
$payment_types = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get currencies
$currencies = ['USD', 'EUR', 'GBP', 'UGX'];

// Handle invoice creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_invoice'])) {
    $student_id = $_POST['student_id'] ?? null;
    $amount = !empty($_POST['amount']) ? (float)$_POST['amount'] : null;
    $currency = $_POST['currency'] ?? 'USD';
    $due_date = $_POST['due_date'] ?? null;
    $description = trim($_POST['description'] ?? '');
    $payment_type_id = $_POST['payment_type_id'] ?? null;
    
    // Validate form data
    if (!$student_id || $amount === null || $amount <= 0 || !$due_date) {
        $error = "Student, amount, and due date are required fields.";
    } else {
        try {
            // Insert invoice
            $stmt = $pdo->prepare("INSERT INTO invoices (
                student_id, amount, currency, due_date, status, description, created_at, updated_at
            ) VALUES (?, ?, ?, ?, 'unpaid', ?, NOW(), NOW())");
            
            $stmt->execute([
                $student_id, $amount, $currency, $due_date, $description
            ]);
            
            $invoice_id = $pdo->lastInsertId();
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "invoice_created",
                "Admin {$admin['first_name']} {$admin['last_name']} created invoice #{$invoice_id} for student ID {$student_id}"
            ]);
            
            $success = "Invoice created successfully!";
            header('Location: admin-invoices.php?success=created');
            exit;
            
        } catch (Exception $e) {
            $error = "Failed to create invoice. Please try again.";
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Create Invoice - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        .section-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3fb7fe;
        }
        .invoice-preview {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .invoice-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        .invoice-total {
            font-weight: 700;
            font-size: 1.2em;
            color: #3fb7fe;
            padding-top: 10px;
            margin-top: 10px;
            border-top: 2px solid #3fb7fe;
        }
    </style>
</head>
<body>
    <?php include 'admin-navbar.php'; ?>
    
    <div class="container py-5">
        <div class="section-title position-relative mb-4">
            <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Financial Management</h6>
            <h1 class="display-5">Create New Invoice</h1>
        </div>
        
        <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <form method="POST">
            <!-- Student Information -->
            <div class="form-section">
                <h5 class="section-title">Student Information</h5>
                <div class="form-group">
                    <label>Student *</label>
                    <select name="student_id" class="form-control" required>
                        <option value="">Select Student</option>
                        <?php foreach ($students as $student): ?>
                        <option value="<?= $student['id'] ?>">
                            <?= htmlspecialchars($student['first_name'] . ' ' . $student['last_name']) ?> (<?= htmlspecialchars($student['email']) ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <!-- Invoice Details -->
            <div class="form-section">
                <h5 class="section-title">Invoice Details</h5>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Amount *</label>
                        <div class="input-group">
                            <input type="number" name="amount" class="form-control" step="0.01" min="0" required>
                            <div class="input-group-append">
                                <select name="currency" class="input-group-text">
                                    <?php foreach ($currencies as $curr): ?>
                                    <option value="<?= $curr ?>" <?= $curr === 'USD' ? 'selected' : '' ?>>
                                        <?= $curr ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label>Due Date *</label>
                        <input type="date" name="due_date" class="form-control" required>
                    </div>
                </div>
                <div class="form-group">
                    <label>Payment Type</label>
                    <select name="payment_type_id" class="form-control">
                        <option value="">Select Payment Type</option>
                        <?php foreach ($payment_types as $type): ?>
                        <option value="<?= $type['id'] ?>"><?= htmlspecialchars($type['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" class="form-control" rows="3" placeholder="Enter invoice description..."></textarea>
                </div>
            </div>
            
            <!-- Invoice Preview -->
            <div class="form-section">
                <h5 class="section-title">Invoice Preview</h5>
                <div class="invoice-preview">
                    <div class="d-flex justify-content-between mb-3">
                        <h5>INVOICE</h5>
                        <span><?= date('Y-m-d') ?></span>
                    </div>
                    <div class="mb-3">
                        <p><strong>Bill To:</strong></p>
                        <p id="previewStudent">Select a student</p>
                    </div>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Description</th>
                                    <th>Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td id="previewDescription">Service Fee</td>
                                    <td id="previewAmount">$0.00</td>
                                </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td class="text-right"><strong>Total Due:</strong></td>
                                    <td class="invoice-total" id="previewTotal">$0.00</td>
                                </tr>
                                <tr>
                                    <td class="text-right"><strong>Due Date:</strong></td>
                                    <td id="previewDueDate">-</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Form Submission -->
            <div class="text-center">
                <button type="submit" name="create_invoice" class="btn btn-primary btn-lg px-5">Create Invoice</button>
                <a href="admin-invoices.php" class="btn btn-outline-secondary ml-2">Cancel</a>
            </div>
        </form>
    </div>

    <?php include 'footer.php'; ?>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
    <script>
        // Update invoice preview
        function updatePreview() {
            const studentSelect = document.querySelector('select[name="student_id"]');
            const amountInput = document.querySelector('input[name="amount"]');
            const currencySelect = document.querySelector('select[name="currency"]');
            const dueDateInput = document.querySelector('input[name="due_date"]');
            const descriptionInput = document.querySelector('textarea[name="description"]');
            
            const studentOption = studentSelect.options[studentSelect.selectedIndex];
            const studentName = studentOption ? studentOption.text.split(' (')[0] : 'Select a student';
            const amount = amountInput.value || '0';
            const currency = currencySelect.value;
            const dueDate = dueDateInput.value ? new Date(dueDateInput.value).toLocaleDateString() : '-';
            const description = descriptionInput.value || 'Service Fee';
            
            document.getElementById('previewStudent').textContent = studentName;
            document.getElementById('previewDescription').textContent = description;
            document.getElementById('previewAmount').textContent = `${currency}${parseFloat(amount).toFixed(2)}`;
            document.getElementById('previewTotal').textContent = `${currency}${parseFloat(amount).toFixed(2)}`;
            document.getElementById('previewDueDate').textContent = dueDate;
        }
        
        // Add event listeners
        document.addEventListener('DOMContentLoaded', function() {
            const inputs = document.querySelectorAll('select[name="student_id"], input[name="amount"], select[name="currency"], input[name="due_date"], textarea[name="description"]');
            
            inputs.forEach(input => {
                input.addEventListener('input', updatePreview);
            });
            
            // Initial preview update
            updatePreview();
        });
    </script>
</body>
</html>