<?php
/**
 * Admin Coupons Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Coupons';

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM coupons WHERE id = ?");
        $stmt->execute([$id]);
        set_flash_message('Coupon deleted successfully!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to delete coupon.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        set_flash_message('Invalid request.', 'error');
    } else {
        $id = (int)($_POST['id'] ?? 0);
        $code = strtoupper(sanitize($_POST['code'] ?? ''));
        $discount_type = sanitize($_POST['discount_type'] ?? 'percentage');
        $discount_value = (float)($_POST['discount_value'] ?? 0);
        $max_discount = (float)($_POST['max_discount'] ?? 0);
        $min_order = (float)($_POST['min_order'] ?? 0);
        $usage_limit = (int)($_POST['usage_limit'] ?? 0);
        $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (empty($code)) {
            set_flash_message('Coupon code is required.', 'error');
        } elseif ($discount_value <= 0) {
            set_flash_message('Discount value must be greater than 0.', 'error');
        } else {
            try {
                if ($id) {
                    // Update
                    $stmt = $pdo->prepare("UPDATE coupons SET code = ?, discount_type = ?, discount_value = ?, max_discount = ?, min_order = ?, usage_limit = ?, start_date = ?, end_date = ?, is_active = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$code, $discount_type, $discount_value, $max_discount, $min_order, $usage_limit, $start_date, $end_date, $is_active, $id]);
                    set_flash_message('Coupon updated successfully!', 'success');
                } else {
                    // Insert
                    $stmt = $pdo->prepare("INSERT INTO coupons (code, discount_type, discount_value, max_discount, min_order, usage_limit, start_date, end_date, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
                    $stmt->execute([$code, $discount_type, $discount_value, $max_discount, $min_order, $usage_limit, $start_date, $end_date, $is_active]);
                    set_flash_message('Coupon added successfully!', 'success');
                }
            } catch (PDOException $e) {
                if ($e->getCode() == 23000) {
                    set_flash_message('Coupon code already exists.', 'error');
                } else {
                    set_flash_message('Failed to save coupon.', 'error');
                }
            }
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Get coupons
$stmt = $pdo->query("SELECT * FROM coupons ORDER BY created_at DESC");
$coupons = $stmt->fetchAll();

// Get coupon for edit
$edit_coupon = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM coupons WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_coupon = $stmt->fetch();
}

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-ticket-alt me-2"></i>Coupons</h1>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#couponModal">
            <i class="fas fa-plus me-2"></i>Add Coupon
        </button>
    </div>
    
    <!-- Coupons Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Code</th>
                            <th>Discount</th>
                            <th>Usage</th>
                            <th>Valid Period</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($coupons as $coupon): 
                            $is_expired = $coupon['end_date'] && strtotime($coupon['end_date']) < time();
                            $is_not_started = $coupon['start_date'] && strtotime($coupon['start_date']) > time();
                        ?>
                        <tr>
                            <td>
                                <code class="fs-6"><?php echo $coupon['code']; ?></code>
                            </td>
                            <td>
                                <?php if ($coupon['discount_type'] === 'percentage'): ?>
                                    <?php echo $coupon['discount_value']; ?>%
                                    <?php if ($coupon['max_discount'] > 0): ?>
                                    <small class="d-block text-muted">Max: <?php echo format_price($coupon['max_discount']); ?></small>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <?php echo format_price($coupon['discount_value']); ?>
                                <?php endif; ?>
                                <?php if ($coupon['min_order'] > 0): ?>
                                <small class="d-block text-muted">Min order: <?php echo format_price($coupon['min_order']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo $coupon['usage_count']; ?>
                                <?php if ($coupon['usage_limit'] > 0): ?>
                                / <?php echo $coupon['usage_limit']; ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($coupon['start_date']): ?>
                                <small>From: <?php echo format_date($coupon['start_date']); ?></small><br>
                                <?php endif; ?>
                                <?php if ($coupon['end_date']): ?>
                                <small>To: <?php echo format_date($coupon['end_date']); ?></small>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($is_expired): ?>
                                <span class="badge bg-secondary">Expired</span>
                                <?php elseif ($is_not_started): ?>
                                <span class="badge bg-info">Scheduled</span>
                                <?php else: ?>
                                <span class="badge bg-<?php echo $coupon['is_active'] ? 'success' : 'secondary'; ?>">
                                    <?php echo $coupon['is_active'] ? 'Active' : 'Inactive'; ?>
                                </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="?edit=<?php echo $coupon['id']; ?>" class="btn btn-sm btn-primary" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete=<?php echo $coupon['id']; ?>" class="btn btn-sm btn-danger confirm-delete" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Coupon Modal -->
<div class="modal fade" id="couponModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo $edit_coupon ? 'Edit Coupon' : 'Add Coupon'; ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <?php echo csrf_field(); ?>
                    
                    <?php if ($edit_coupon): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_coupon['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Code <span class="text-danger">*</span></label>
                            <input type="text" name="code" class="form-control text-uppercase" 
                                   value="<?php echo $edit_coupon ? sanitize($edit_coupon['code']) : ''; ?>" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Discount Type</label>
                            <select name="discount_type" class="form-select">
                                <option value="percentage" <?php echo ($edit_coupon && $edit_coupon['discount_type'] === 'percentage') ? 'selected' : ''; ?>>Percentage (%)</option>
                                <option value="fixed" <?php echo ($edit_coupon && $edit_coupon['discount_type'] === 'fixed') ? 'selected' : ''; ?>>Fixed Amount</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Discount Value <span class="text-danger">*</span></label>
                            <input type="number" name="discount_value" class="form-control" 
                                   value="<?php echo $edit_coupon ? $edit_coupon['discount_value'] : ''; ?>" 
                                   step="0.01" min="0.01" required>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Max Discount (for percentage)</label>
                            <input type="number" name="max_discount" class="form-control" 
                                   value="<?php echo $edit_coupon ? $edit_coupon['max_discount'] : '0'; ?>" 
                                   step="0.01" min="0">
                            <small class="text-muted">0 = no limit</small>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Minimum Order Amount</label>
                            <input type="number" name="min_order" class="form-control" 
                                   value="<?php echo $edit_coupon ? $edit_coupon['min_order'] : '0'; ?>" 
                                   step="0.01" min="0">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Usage Limit</label>
                            <input type="number" name="usage_limit" class="form-control" 
                                   value="<?php echo $edit_coupon ? $edit_coupon['usage_limit'] : '0'; ?>" 
                                   min="0">
                            <small class="text-muted">0 = unlimited</small>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Start Date</label>
                            <input type="date" name="start_date" class="form-control" 
                                   value="<?php echo $edit_coupon ? $edit_coupon['start_date'] : ''; ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">End Date</label>
                            <input type="date" name="end_date" class="form-control" 
                                   value="<?php echo $edit_coupon ? $edit_coupon['end_date'] : ''; ?>">
                        </div>
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="is_active" id="is_active" 
                               <?php echo (!$edit_coupon || $edit_coupon['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><?php echo $edit_coupon ? 'Update' : 'Add'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if ($edit_coupon): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var modal = new bootstrap.Modal(document.getElementById('couponModal'));
    modal.show();
});
</script>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>
