<?php
/**
 * PENALTY SETTINGS PAGE - ADMIN (DAY-BASED)
 * File: admin/penalty-settings.php
 * UPDATED: Day-based penalty tiers (1-7+ days)
 */

require_once '../app/Core/init.php';

// Require admin authentication
Auth::requireAdmin();

$penaltyModel = new PenaltySettings();
$db = Database::getInstance();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_settings') {
    
    // Validate inputs
    $penalty_source = $_POST['penalty_source'] ?? 'admin';
    $admin_commission_from_penalty = floatval($_POST['admin_commission_from_penalty'] ?? 30);
    
    // Day-based penalties
    $penalty_7plus_days = floatval($_POST['penalty_7plus_days'] ?? 0);
    $penalty_6_days = floatval($_POST['penalty_6_days'] ?? 0);
    $penalty_5_days = floatval($_POST['penalty_5_days'] ?? 0);
    $penalty_4_days = floatval($_POST['penalty_4_days'] ?? 0);
    $penalty_3_days = floatval($_POST['penalty_3_days'] ?? 0);
    $penalty_2_days = floatval($_POST['penalty_2_days'] ?? 20);
    $penalty_1_day = floatval($_POST['penalty_1_day'] ?? 50);
    $penalty_same_day = floatval($_POST['penalty_same_day'] ?? 100);
    
    // Validation
    $errors = [];
    
    if ($admin_commission_from_penalty < 0 || $admin_commission_from_penalty > 100) {
        $errors[] = "Admin commission must be between 0 and 100";
    }
    
    if (empty($errors)) {
        $success = $penaltyModel->updateSettings([
            'penalty_source' => $penalty_source,
            'admin_commission_from_penalty' => $admin_commission_from_penalty,
            'penalty_7plus_days' => $penalty_7plus_days,
            'penalty_6_days' => $penalty_6_days,
            'penalty_5_days' => $penalty_5_days,
            'penalty_4_days' => $penalty_4_days,
            'penalty_3_days' => $penalty_3_days,
            'penalty_2_days' => $penalty_2_days,
            'penalty_1_day' => $penalty_1_day,
            'penalty_same_day' => $penalty_same_day,
            'updated_by' => Auth::id()
        ]);
        
        if ($success) {
            flash('success', 'Penalty settings updated successfully!', 'success');
        } else {
            flash('error', 'Failed to update penalty settings', 'danger');
        }
        
        redirect($_SERVER['PHP_SELF']);
    } else {
        foreach ($errors as $error) {
            flash('error', $error, 'danger');
        }
    }
}

// Get current settings
$settings = $penaltyModel->getSettings();

// If no settings exist, use defaults
if (!$settings) {
    $settings = [
        'penalty_source' => 'admin',
        'admin_commission_from_penalty' => 30.00,
        'penalty_7plus_days' => 0.00,
        'penalty_6_days' => 0.00,
        'penalty_5_days' => 0.00,
        'penalty_4_days' => 0.00,
        'penalty_3_days' => 0.00,
        'penalty_2_days' => 20.00,
        'penalty_1_day' => 50.00,
        'penalty_same_day' => 100.00
    ];
}

// Get cancellation statistics
$stats = $db->fetch("
    SELECT 
        COUNT(*) as total_cancellations,
        COALESCE(SUM(cancellation_fee), 0) as total_penalty_collected,
        COALESCE(SUM(cancellation_fee_to_admin), 0) as admin_earnings,
        COALESCE(SUM(cancellation_fee_to_vendor), 0) as vendor_earnings,
        COALESCE(SUM(refund_amount), 0) as total_refunded
    FROM orders 
    WHERE status = 'cancelled' 
    AND payment_status = 'paid'
");

$page_title = "Penalty Settings - " . APP_NAME;
$active_menu = "penalty-settings";

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-exclamation-triangle"></i> Cancellation Penalty Settings</h1>
            <p class="text-muted">Configure day-based cancellation policies and penalties</p>
        </div>
    </div>

    <div class="content">
        
        <!-- Statistics Cards -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-danger text-white">
                    <div class="card-body">
                        <h6 class="mb-2">Total Cancellations</h6>
                        <h2 class="mb-0"><?= number_format($stats['total_cancellations'] ?? 0) ?></h2>
                        <small>Paid orders cancelled</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <h6 class="mb-2">Penalties Collected</h6>
                        <h2 class="mb-0">₦<?= number_format($stats['total_penalty_collected'] ?? 0, 0) ?></h2>
                        <small>Total penalty fees</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h6 class="mb-2">Admin Earnings</h6>
                        <h2 class="mb-0">₦<?= number_format($stats['admin_earnings'] ?? 0, 0) ?></h2>
                        <small>From penalties</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <h6 class="mb-2">Vendor Share</h6>
                        <h2 class="mb-0">₦<?= number_format($stats['vendor_earnings'] ?? 0, 0) ?></h2>
                        <small>From penalties</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Settings Form -->
        <div class="row">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-cog"></i> Day-Based Penalty Configuration</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="csrf_token" value="<?= Security::generateToken() ?>">
                            <input type="hidden" name="action" value="update_settings">
                            
                            <!-- Penalty Source -->
                            <div class="form-group mb-4">
                                <label class="form-label"><strong>Penalty Source</strong></label>
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle"></i> Select who sets the cancellation penalty percentage
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="penalty_source" 
                                           id="penalty_admin" value="admin" 
                                           <?= $settings['penalty_source'] === 'admin' ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="penalty_admin">
                                        <strong>Admin Set Penalty</strong> - Use admin-configured penalty percentage for all items (Current Phase)
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="penalty_source" 
                                           id="penalty_vendor" value="vendor" 
                                           <?= $settings['penalty_source'] === 'vendor' ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="penalty_vendor">
                                        <strong>Vendor Set Penalty</strong> - Allow vendors to set their own penalty percentage (Phase 2 - Coming Soon)
                                    </label>
                                </div>
                            </div>

                            <hr>

                            <!-- Admin Commission from Penalty -->
                            <div class="form-group mb-4">
                                <label class="form-label"><strong>Admin Commission from Penalty</strong></label>
                                <div class="input-group">
                                    <input type="number" name="admin_commission_from_penalty" class="form-control" 
                                           step="0.01" min="0" max="100" 
                                           value="<?= $settings['admin_commission_from_penalty'] ?>" required>
                                    <span class="input-group-text">%</span>
                                </div>
                                <small class="text-muted">Percentage of penalty fee that goes to admin (remaining goes to vendor)</small>
                                
                                <!-- Example Calculation -->
                                <div class="alert alert-light mt-2">
                                    <strong>Example:</strong><br>
                                    Rental: ₦60,000 | Penalty: 20% = ₦12,000<br>
                                    Admin gets: <?= $settings['admin_commission_from_penalty'] ?>% = ₦<?= number_format((12000 * $settings['admin_commission_from_penalty'] / 100), 2) ?><br>
                                    Vendor gets: <?= 100 - $settings['admin_commission_from_penalty'] ?>% = ₦<?= number_format((12000 * (100 - $settings['admin_commission_from_penalty']) / 100), 2) ?>
                                </div>
                            </div>

                            <hr>

                            <!-- Day-Based Penalties -->
                            <h5 class="mb-3"><i class="fas fa-calendar-alt"></i> Day-Based Penalty Rates</h5>
                            <div class="alert alert-warning">
                                <i class="fas fa-lightbulb"></i> <strong>How it works:</strong> Set penalty percentage based on how many days before the booking start date the customer cancels.
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>7+ Days Before</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_7plus_days" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_7plus_days'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                        <small class="text-success">Recommended: 0% (Free cancellation)</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>6 Days Before</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_6_days" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_6_days'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>5 Days Before</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_5_days" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_5_days'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>4 Days Before</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_4_days" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_4_days'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>3 Days Before</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_3_days" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_3_days'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>2 Days Before</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_2_days" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_2_days'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                        <small class="text-muted">Recommended: 20%</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>1 Day Before (24-48 hours)</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_1_day" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_1_day'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                        <small class="text-muted">Recommended: 50%</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group mb-3">
                                        <label><strong>Same Day (Less than 24 hours)</strong></label>
                                        <div class="input-group">
                                            <input type="number" name="penalty_same_day" class="form-control" 
                                                   step="0.01" min="0" max="100" 
                                                   value="<?= $settings['penalty_same_day'] ?>">
                                            <span class="input-group-text">%</span>
                                        </div>
                                        <small class="text-danger">Recommended: 100% (Full penalty)</small>
                                    </div>
                                </div>
                            </div>

                            <hr>

                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-save"></i> Save Settings
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Info Sidebar -->
            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h5 class="mb-0"><i class="fas fa-info-circle"></i> How It Works</h5>
                    </div>
                    <div class="card-body">
                        <h6>Day-Based Calculation</h6>
                        <p>The system calculates the number of <strong>full days</strong> between cancellation date and booking start date.</p>
                        
                        <h6 class="mt-3">Example:</h6>
                        <ul>
                            <li><strong>Booking:</strong> March 4-5</li>
                            <li><strong>Cancelled:</strong> February 26</li>
                            <li><strong>Days until start:</strong> 6 days</li>
                            <li><strong>Penalty:</strong> Uses "6 Days Before" rate</li>
                        </ul>

                        <hr>

                        <h6>Important Notes</h6>
                        <ul class="mb-0">
                            <li>Penalty applies to <strong>rental amount only</strong></li>
                            <li>Security deposit is <strong>always fully refunded</strong></li>
                            <li>Admin earns commission from penalties</li>
                            <li>Vendor gets remaining penalty amount</li>
                            <li>Cancel button hides on booking start date</li>
                        </ul>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header">
                        <h6 class="mb-0">Current Policy</h6>
                    </div>
                    <div class="card-body">
                        <?= $penaltyModel->getPolicyText() ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/layouts/admin/footer.php'; ?>