<?php
require_once __DIR__ . '/../config.php';
requireRole(['procurement']);

$pageTitle = 'Supplier Forecast Report';
require_once __DIR__ . '/../includes/admin-header.php';
require_once __DIR__ . '/../lib/logic.php';

$pdo = getDBConnection();

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $id = $_POST['id'] ?? null;
        $supplierId = $_POST['supplier_id'] ?? '';
        $supplierName = $_POST['supplier_name'] ?? '';
        $itemCode = $_POST['item_code'] ?? '';
        $itemDescription = $_POST['item_description'] ?? '';
        $forecastMonth = $_POST['forecast_month'] ?? '';
        $quantityForecast = floatval($_POST['quantity_forecast'] ?? 0);
        $unitPrice = floatval($_POST['unit_price'] ?? 0);
        $notes = $_POST['notes'] ?? '';

        $estimatedValue = $quantityForecast * $unitPrice;

        if ($id) {
            $stmt = $pdo->prepare("UPDATE supplier_forecast SET supplier_id = ?, supplier_name = ?, item_code = ?, item_description = ?, forecast_month = ?, quantity_forecast = ?, unit_price = ?, estimated_value = ?, notes = ? WHERE id = ?");
            $stmt->execute([$supplierId, $supplierName, $itemCode, $itemDescription, $forecastMonth, $quantityForecast, $unitPrice, $estimatedValue, $notes, $id]);
            $message = 'Record updated successfully';
        } else {
            $stmt = $pdo->prepare("INSERT INTO supplier_forecast (supplier_id, supplier_name, item_code, item_description, forecast_month, quantity_forecast, unit_price, estimated_value, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$supplierId, $supplierName, $itemCode, $itemDescription, $forecastMonth, $quantityForecast, $unitPrice, $estimatedValue, $notes]);
            $message = 'Record added successfully';
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? 0;
        $stmt = $pdo->prepare("DELETE FROM supplier_forecast WHERE id = ?");
        $stmt->execute([$id]);
        $message = 'Record deleted successfully';
    }
}

$supplierFilter = $_GET['supplier'] ?? '';
$monthFilter = $_GET['month'] ?? '';
$searchTerm = $_GET['search'] ?? '';

$sql = "SELECT * FROM supplier_forecast WHERE 1=1";
$params = [];

if (!empty($supplierFilter)) {
    $sql .= " AND supplier_id = ?";
    $params[] = $supplierFilter;
}

if (!empty($monthFilter)) {
    $sql .= " AND forecast_month = ?";
    $params[] = $monthFilter;
}

if (!empty($searchTerm)) {
    $sql .= " AND (item_code LIKE ? OR item_description LIKE ? OR supplier_name LIKE ?)";
    $searchParam = "%$searchTerm%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$sql .= " ORDER BY forecast_month DESC, supplier_name ASC, item_code ASC";

if (!empty($params)) {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $forecasts = $stmt->fetchAll();
} else {
    try {
        $forecasts = $pdo->query($sql)->fetchAll();
    } catch (PDOException $e) {
        $forecasts = [];
    }
}

$suppliers = $pdo->query("SELECT DISTINCT SupplierID, SupplierName FROM suppliers WHERE SupplierID IS NOT NULL ORDER BY SupplierName")->fetchAll();
try {
    $months = $pdo->query("SELECT DISTINCT forecast_month FROM supplier_forecast WHERE forecast_month IS NOT NULL ORDER BY forecast_month DESC")->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    $months = [];
}
try {
    $statsSql = "SELECT 
        COUNT(*) as total_records,
        SUM(quantity_forecast) as total_quantity,
        SUM(estimated_value) as total_value
    FROM supplier_forecast";
    $stats = $pdo->query($statsSql)->fetch();
} catch (PDOException $e) {
    $stats = ['total_records' => 0, 'total_quantity' => 0, 'total_value' => 0];
}

$editRecord = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM supplier_forecast WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editRecord = $stmt->fetch();
}
?>

<style>
    .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }
    .stat-card.quantity {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
    .stat-card.value {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
    .stat-value {
        font-size: 2rem;
        font-weight: bold;
        margin-top: 5px;
    }
    .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
        display: none;
        align-items: center;
        justify-content: center;
    }
    .modal-overlay.show {
        display: flex;
    }
    .modal-content {
        background: white;
        border-radius: 8px;
        padding: 24px;
        max-width: 600px;
        width: 90%;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 4px 20px rgba(0,0,0,0.2);
    }
    .dropdown-container {
        position: relative;
        display: inline-block;
    }
    .export-dropdown {
        position: absolute;
        right: 0;
        top: 100%;
        background: white;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 100;
        min-width: 150px;
    }
    .export-dropdown a {
        display: block;
        padding: 10px 15px;
        text-decoration: none;
        color: #333;
    }
    .export-dropdown a:hover {
        background: #f5f5f5;
    }
</style>

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

<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-label">Total Forecast Records</div>
            <div class="stat-value"><?php echo number_format($stats['total_records'] ?? 0); ?></div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card quantity">
            <div class="stat-label">Total Forecast Quantity</div>
            <div class="stat-value"><?php echo number_format($stats['total_quantity'] ?? 0, 2); ?></div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card value">
            <div class="stat-label">Total Estimated Value</div>
            <div class="stat-value">$<?php echo number_format($stats['total_value'] ?? 0, 2); ?></div>
        </div>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-funnel me-2"></i>Filters</h5>
        <div class="dropdown-container">
            <button class="btn btn-success dropdown-toggle me-2" onclick="toggleExportDropdown(this)">
                <i class="bi bi-download me-1"></i> Export
            </button>
            <div class="export-dropdown hidden" style="display: none;">
                <a href="#" onclick="exportData('supplier_forecast', {supplier: '<?php echo $supplierFilter; ?>', month: '<?php echo $monthFilter; ?>'}); return false;">Export to Excel</a>
                <a href="#" onclick="exportToCSV('supplier_forecast', {supplier: '<?php echo $supplierFilter; ?>', month: '<?php echo $monthFilter; ?>'}); return false;">Export to CSV</a>
            </div>
        </div>
        <div class="dropdown-container">
            <button class="btn btn-primary" onclick="showImportModal('supplier_forecast')">
                <i class="bi bi-upload me-1"></i> Import
            </button>
        </div>
    </div>
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <input type="text" name="search" class="form-control" placeholder="Search..." value="<?php echo htmlspecialchars($searchTerm); ?>">
            </div>
            <div class="col-md-3">
                <select name="supplier" class="form-select">
                    <option value="">All Suppliers</option>
                    <?php foreach ($suppliers as $sup): ?>
                        <option value="<?php echo htmlspecialchars($sup['supplier_id']); ?>" <?php echo $supplierFilter === $sup['supplier_id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($sup['supplier_name'] ?? $sup['supplier_id']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <select name="month" class="form-select">
                    <option value="">All Months</option>
                    <?php foreach ($months as $month): ?>
                        <option value="<?php echo htmlspecialchars($month); ?>" <?php echo $monthFilter === $month ? 'selected' : ''; ?>><?php echo htmlspecialchars($month); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-primary me-2"><i class="bi bi-search"></i> Filter</button>
                <a href="supplier_forecast.php" class="btn btn-outline-secondary"><i class="bi bi-x-circle"></i> Clear</a>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="bi bi-graph-up me-2"></i>Supplier Forecast Report</h5>
        <button class="btn btn-primary" onclick="openFormModal()">
            <i class="bi bi-plus-lg me-1"></i> Add New
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($forecasts)): ?>
            <p class="text-muted">No forecast records found</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Supplier</th>
                            <th>Item Code</th>
                            <th>Item Description</th>
                            <th>Forecast Month</th>
                            <th>Quantity</th>
                            <th>Unit Price</th>
                            <th>Est. Value</th>
                            <th>Notes</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($forecasts as $forecast): ?>
                        <tr>
                            <td><?php echo sanitize($forecast['supplier_name'] ?? $forecast['supplier_id'] ?? '-'); ?></td>
                            <td><?php echo sanitize($forecast['item_code'] ?? '-'); ?></td>
                            <td><?php echo sanitize($forecast['item_description'] ?? '-'); ?></td>
                            <td><?php echo $forecast['forecast_month'] ?? '-'; ?></td>
                            <td><?php echo number_format($forecast['quantity_forecast'] ?? 0, 2); ?></td>
                            <td>$<?php echo number_format($forecast['unit_price'] ?? 0, 2); ?></td>
                            <td>$<?php echo number_format($forecast['estimated_value'] ?? 0, 2); ?></td>
                            <td><?php echo sanitize($forecast['notes'] ?? '-'); ?></td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick='editRecord(<?php echo json_encode($forecast); ?>)'>
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this record?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?php echo $forecast['id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<div id="formModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="margin: 0;"><?php echo $editRecord ? 'Edit' : 'Add'; ?> Forecast</h3>
            <button onclick="closeFormModal()" style="background: none; border: none; font-size: 24px; cursor: pointer; padding: 0; line-height: 1;">&times;</button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" value="<?php echo $editRecord['id'] ?? ''; ?>">
            <div class="mb-3">
                <label class="form-label">Supplier</label>
                <select name="supplier_id" class="form-select" required>
                    <option value="">Select Supplier</option>
                    <?php foreach ($suppliers as $sup): ?>
                        <option value="<?php echo htmlspecialchars($sup['supplier_id']); ?>" <?php echo ($editRecord['supplier_id'] ?? '') === $sup['supplier_id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($sup['supplier_name'] ?? $sup['supplier_id']); ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="text" name="supplier_name" class="form-control mt-2" placeholder="Or enter supplier name" value="<?php echo htmlspecialchars($editRecord['supplier_name'] ?? ''); ?>">
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Item Code</label>
                    <input type="text" name="item_code" class="form-control" value="<?php echo htmlspecialchars($editRecord['item_code'] ?? ''); ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Item Description</label>
                    <input type="text" name="item_description" class="form-control" value="<?php echo htmlspecialchars($editRecord['item_description'] ?? ''); ?>">
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Forecast Month (YYYY-MM)</label>
                    <input type="text" name="forecast_month" class="form-control" placeholder="2026-04" value="<?php echo htmlspecialchars($editRecord['forecast_month'] ?? ''); ?>" required pattern="\d{4}-\d{2}">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Quantity Forecast</label>
                    <input type="number" step="0.01" name="quantity_forecast" class="form-control" value="<?php echo $editRecord['quantity_forecast'] ?? ''; ?>" required>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Unit Price</label>
                    <input type="number" step="0.01" name="unit_price" class="form-control" value="<?php echo $editRecord['unit_price'] ?? ''; ?>" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Estimated Value</label>
                    <input type="text" class="form-control" readonly value="<?php echo number_format(($editRecord['estimated_value'] ?? 0), 2); ?>">
                </div>
            </div>
            <div class="mb-3">
                <label class="form-label">Notes</label>
                <textarea name="notes" class="form-control" rows="2"><?php echo htmlspecialchars($editRecord['notes'] ?? ''); ?></textarea>
            </div>
            <div style="display: flex; gap: 12px; justify-content: flex-end;">
                <button type="button" onclick="closeFormModal()" class="btn btn-secondary">Cancel</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/admin-import-modal.php'; ?>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>

<script src="../assets/js/export-import.js"></script>
<script>
function toggleExportDropdown(btn) {
    const dropdown = btn.parentElement.querySelector('.export-dropdown');
    if (!dropdown) return;
    dropdown.classList.toggle('hidden');
    dropdown.style.display = dropdown.classList.contains('hidden') ? 'none' : 'block';
}

document.addEventListener('click', function(e) {
    if (!e.target.closest('.dropdown-container')) {
        document.querySelectorAll('.export-dropdown').forEach(d => {
            d.classList.add('hidden');
            d.style.display = 'none';
        });
    }
});

function openFormModal() {
    document.getElementById('formModal').classList.add('show');
}

function closeFormModal() {
    document.getElementById('formModal').classList.remove('show');
    window.location.href = 'supplier_forecast.php';
}

function editRecord(record) {
    document.getElementById('formModal').classList.add('show');
}
</script>

<?php if ($editRecord): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    openFormModal();
});
</script>
<?php endif; ?>