<?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 = '';

// Handle payment type creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_payment_type'])) {
    $name = trim($_POST['name'] ?? '');
    $description = $_POST['description'] ?? '';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Validate form data
    if (empty($name)) {
        $error = "Payment type name is required.";
    } else {
        try {
            // Check if payment type already exists
            $stmt = $pdo->prepare("SELECT id FROM payment_types WHERE name = ?");
            $stmt->execute([$name]);
            if ($stmt->fetch()) {
                $error = "A payment type with this name already exists.";
            } else {
                // Create payment type
                $stmt = $pdo->prepare("INSERT INTO payment_types (name, description, is_active, created_at, updated_at) 
                                      VALUES (?, ?, ?, NOW(), NOW())");
                $stmt->execute([$name, $description, $is_active]);
                
                // Log the activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, created_at
                ) VALUES (?, ?, ?, NOW())")->execute([
                    $_SESSION['user_id'],
                    "payment_type_created",
                    "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} created payment type: {$name}"
                ]);
                
                $success = "Payment type created successfully!";
                
                // Clear form data
                $_POST = array();
                
            }
        } catch (Exception $e) {
            $error = "Failed to create payment type. Please try again.";
        }
    }
}

// Handle payment type update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_payment_type'])) {
    $id = $_POST['id'] ?? null;
    $name = trim($_POST['name'] ?? '');
    $description = $_POST['description'] ?? '';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Validate form data
    if (!$id || empty($name)) {
        $error = "Payment type ID and name are required.";
    } else {
        try {
            // Check if payment type exists
            $stmt = $pdo->prepare("SELECT id FROM payment_types WHERE id = ?");
            $stmt->execute([$id]);
            if (!$stmt->fetch()) {
                $error = "Payment type not found.";
            } else {
                // Update payment type
                $stmt = $pdo->prepare("UPDATE payment_types SET name = ?, description = ?, is_active = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$name, $description, $is_active, $id]);
                
                // Log the activity
                $pdo->prepare("INSERT INTO activities (
                    user_id, activity_type, description, created_at
                ) VALUES (?, ?, ?, NOW())")->execute([
                    $_SESSION['user_id'],
                    "payment_type_updated",
                    "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} updated payment type: {$name}"
                ]);
                
                $success = "Payment type updated successfully!";
            }
        } catch (Exception $e) {
            $error = "Failed to update payment type. Please try again.";
        }
    }
}

// Handle payment type deletion
if (isset($_GET['delete']) && !empty($_GET['delete'])) {
    $payment_type_id = $_GET['delete'];
    
    try {
        // Check if this payment type is being used in any payments
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM payments WHERE payment_type_id = ?");
        $stmt->execute([$payment_type_id]);
        $usage_count = $stmt->fetchColumn();
        
        if ($usage_count > 0) {
            $error = "Cannot delete this payment type as it is being used in {$usage_count} payment(s).";
        } else {
            // Delete the payment type
            $stmt = $pdo->prepare("DELETE FROM payment_types WHERE id = ?");
            $stmt->execute([$payment_type_id]);
            
            // Log the activity
            $pdo->prepare("INSERT INTO activities (
                user_id, activity_type, description, created_at
            ) VALUES (?, ?, ?, NOW())")->execute([
                $_SESSION['user_id'],
                "payment_type_deleted",
                "Admin {$_SESSION['first_name']} {$_SESSION['last_name']} deleted payment type with ID: {$payment_type_id}"
            ]);
            
            $success = "Payment type deleted successfully!";
        }
    } catch (Exception $e) {
        $error = "Failed to delete payment type. Please try again.";
    }
}

// Get all payment types
$payment_types = $pdo->query("SELECT * FROM payment_types ORDER BY name")->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM payment_types")->fetchColumn(),
    'active' => $pdo->query("SELECT COUNT(*) FROM payment_types WHERE is_active = 1")->fetchColumn(),
    'inactive' => $pdo->query("SELECT COUNT(*) FROM payment_types WHERE is_active = 0")->fetchColumn(),
];

// Get payment type to edit (if specified)
$edit_payment_type = null;
if (isset($_GET['edit']) && !empty($_GET['edit'])) {
    $edit_id = $_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM payment_types WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_payment_type = $stmt->fetch();
    
    if (!$edit_payment_type) {
        $error = "Payment type not found.";
    }
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Payment Types - 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>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }
        .payment-type-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
        }
        .payment-type-item:last-child {
            border-bottom: none;
        }
        .payment-type-name {
            font-weight: 600;
        }
        .payment-type-description {
            color: #6c757d;
            font-size: 0.9em;
            margin-top: 5px;
        }
    </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">Manage Payment Types</h1>
    </div>

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

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-4 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Types</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <h6>Active</h6>
                    <h3><?= $stats['active'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-4 mb-3">
            <div class="stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <h6>Inactive</h6>
                    <h3><?= $stats['inactive'] ?></h3>
                </div>
            </div>
        </div>
    </div>

    <?php if ($edit_payment_type): ?>
    <!-- Edit Payment Type Form -->
    <div class="section-card">
        <div class="section-header">Edit Payment Type</div>
        <div class="section-body">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $edit_payment_type['id'] ?>">
                <div class="form-group">
                    <label>Name *</label>
                    <input type="text" name="name" class="form-control" 
                           value="<?= htmlspecialchars($edit_payment_type['name']) ?>" required>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($edit_payment_type['description']) ?></textarea>
                </div>
                <div class="form-group">
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" name="is_active" id="is_active" <?= $edit_payment_type['is_active'] ? 'checked' : '' ?>>
                        <label class="custom-control-label" for="is_active">Active</label>
                    </div>
                </div>
                <div class="text-right">
                    <a href="admin-payment-types.php" class="btn btn-outline-secondary">Cancel</a>
                    <button type="submit" name="update_payment_type" class="btn btn-primary">Update Payment Type</button>
                </div>
            </form>
        </div>
    </div>
    <?php else: ?>
    <!-- Create Payment Type Form -->
    <div class="section-card mb-4">
        <div class="section-header">Create New Payment Type</div>
        <div class="section-body">
            <form method="POST">
                <div class="form-group">
                    <label>Name *</label>
                    <input type="text" name="name" class="form-control" 
                           value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>
                </div>
                <div class="form-group">
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" name="is_active" id="is_active" checked>
                        <label class="custom-control-label" for="is_active">Active</label>
                    </div>
                </div>
                <div class="text-right">
                    <button type="submit" name="create_payment_type" class="btn btn-primary">Create Payment Type</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Payment Types List -->
    <div class="section-card">
        <div class="section-header">Payment Types</div>
        <div class="section-body">
            <?php if (empty($payment_types)): ?>
            <div class="text-center py-5">
                <i class="fas fa-money-bill-wave fa-3x text-muted mb-3"></i>
                <p class="text-muted">No payment types found.</p>
            </div>
            <?php else: ?>
            <?php foreach ($payment_types as $pt): ?>
            <div class="payment-type-item">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="payment-type-name"><?= htmlspecialchars($pt['name']) ?></div>
                        <?php if ($pt['description']): ?>
                        <div class="payment-type-description"><?= htmlspecialchars($pt['description']) ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="d-flex align-items-center">
                        <span class="status-badge status-<?= $pt['is_active'] ? 'active' : 'inactive' ?>">
                            <?= $pt['is_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                        <div class="ml-3">
                            <a href="admin-payment-types.php?edit=<?= $pt['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
                            <button class="btn btn-sm btn-danger delete-payment-type" data-id="<?= $pt['id'] ?>" data-name="<?= htmlspecialchars($pt['name']) ?>">Delete</button>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</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>
    $('.delete-payment-type').on('click', function() {
        const paymentTypeId = $(this).data('id');
        const paymentTypeName = $(this).data('name');
        
        if (confirm(`Are you sure you want to delete the payment type "${paymentTypeName}"? This action cannot be undone.`)) {
            window.location.href = 'admin-payment-types.php?delete=' + paymentTypeId;
        }
    });
</script>
</body>
</html>