<?php
/**
 * Remittances
 * Employer remittance management
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();
if (!isEmployer()) {
    header('Location: access_denied.php');
    exit();
}

$employer_id = $_SESSION['employer_id'] ?? $_SESSION['user_id'];
$action = $_GET['action'] ?? 'list';
$message = '';
$messageType = '';

// Get employer details
$employer = $conn->query("SELECT * FROM employers WHERE employer_id = $employer_id")->fetch_assoc();

if (!$employer) {
    header('Location: logout.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'create') {
    $remittance_date = $_POST['remittance_date'] ?? date('Y-m-d');
    $remittance_period = $_POST['remittance_period'];
    $total_amount = $_POST['total_amount'];
    $reference_number = $_POST['reference_number'] ?? null;
    $notes = $_POST['notes'] ?? null;
    
    $sql = "INSERT INTO remittances (employer_id, remittance_date, remittance_period, total_amount, 
                                    reference_number, notes, status, created_by)
            VALUES (?, ?, ?, ?, ?, ?, 'PENDING', ?)";
    $stmt = $conn->prepare($sql);
    $created_by = $_SESSION['user_id'];
    $stmt->bind_param("issdssi", $employer_id, $remittance_date, $remittance_period, $total_amount, 
                      $reference_number, $notes, $created_by);
    
    if ($stmt->execute()) {
        $message = 'Remittance created successfully';
        $messageType = 'success';
        $action = 'list';
    } else {
        $message = 'Failed to create remittance';
        $messageType = 'danger';
    }
}

// Get remittances
$remittances = $conn->query("SELECT * FROM remittances 
                            WHERE employer_id = $employer_id 
                            ORDER BY remittance_date DESC, created_at DESC")->fetch_all(MYSQLI_ASSOC);

$pageTitle = 'Remittances';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Remittances')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="welcome-header" style="background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Remittances</h2>
                                <p>Manage pension contribution remittances</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="remittances.php?action=create" class="btn btn-primary">
                                <i class="ri-bank-line me-2"></i>New Remittance
                            </a>
                        </div>
                    </div>

                    <?php if ($action === 'create'): ?>
                        <div class="row">
                            <div class="col-md-8">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Create Remittance</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Remittance Date <span class="text-danger">*</span></label>
                                                    <input type="date" name="remittance_date" class="form-control" 
                                                           value="<?php echo date('Y-m-d'); ?>" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Remittance Period <span class="text-danger">*</span></label>
                                                    <input type="month" name="remittance_period" class="form-control" 
                                                           value="<?php echo date('Y-m'); ?>" required>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Total Amount (KES) <span class="text-danger">*</span></label>
                                                    <input type="number" name="total_amount" class="form-control" 
                                                           step="0.01" min="0" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Reference Number</label>
                                                    <input type="text" name="reference_number" class="form-control" 
                                                           placeholder="Bank reference, receipt number, etc.">
                                                </div>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Notes</label>
                                                <textarea name="notes" class="form-control" rows="3"></textarea>
                                            </div>
                                            
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-2"></i>Create Remittance
                                            </button>
                                            <a href="remittances.php" class="btn btn-secondary">Cancel</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Remittances History</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <div class="table-responsive">
                                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>Date</th>
                                                        <th>Period</th>
                                                        <th>Amount (KES)</th>
                                                        <th>Reference</th>
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php if (empty($remittances)): ?>
                                                        <tr><td colspan="6" class="text-center">No remittances found</td></tr>
                                                    <?php else: ?>
                                                        <?php foreach ($remittances as $remit): ?>
                                                            <tr>
                                                                <td><?php echo date('d M Y', strtotime($remit['remittance_date'])); ?></td>
                                                                <td><?php echo date('M Y', strtotime($remit['remittance_period'])); ?></td>
                                                                <td><strong>KES <?php echo number_format($remit['total_amount'], 2); ?></strong></td>
                                                                <td><?php echo htmlspecialchars($remit['reference_number'] ?? 'N/A'); ?></td>
                                                                <td><span class="status-badge status-<?php echo strtolower($remit['status']); ?>"><?php echo htmlspecialchars($remit['status']); ?></span></td>
                                                                <td>
                                                                    <a href="remittance_details.php?id=<?php echo $remit['remittance_id']; ?>" class="btn btn-sm btn-info">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
