<?php
session_start();
if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1,4])) {
    header("Location: ../../index.php");
    exit();
}
include('../../includes/config.php');
include('../../includes/header.php');

// Filters
$store_id = $_GET['store_id'] ?? '';
$date_from = $_GET['from_date'] ?? date('Y-m-01');
$date_to = $_GET['to_date'] ?? date('Y-m-d');

// Fetch stores
$stores = $conn->query("SELECT id, store_name FROM stores");

// Prepare base conditions
$whereSales = "status = 'completed' AND created_at BETWEEN ? AND ?";
$wherePurchases = "se.created_at BETWEEN ? AND ?";
$paramsSales = [$date_from, $date_to];
$paramsPurchases = [$date_from, $date_to];
$typesSales = "ss";
$typesPurchases = "ss";

if ($store_id && is_numeric($store_id)) {
    $whereSales .= " AND store_id = ?";
    $paramsSales[] = $store_id;
    $typesSales .= "i";

    $wherePurchases .= " AND se.store_id = ?";
    $paramsPurchases[] = $store_id;
    $typesPurchases .= "i";
}

// 1. Calculate Sales VAT and Taxable Sales (Output VAT)
$sqlSales = "
    SELECT 
        SUM(total_amount - vat_total) AS taxable_sales,
        SUM(vat_total) AS output_vat
    FROM sales_transactions
    WHERE $whereSales
";

// 2. Calculate Purchase VAT and Taxable Purchases (Input VAT)
$sqlPurchases = "
    SELECT 
        SUM(se.cost_price * se.quantity / (1 + p.vat_rate / 100)) AS taxable_purchases,
        SUM((se.cost_price * se.quantity) - (se.cost_price * se.quantity / (1 + p.vat_rate / 100))) AS input_vat
    FROM stock_entries se
    JOIN products p ON se.product_id = p.id
    WHERE $wherePurchases
";

// Execute sales VAT query
$stmtSales = $conn->prepare($sqlSales);
$stmtSales->bind_param($typesSales, ...$paramsSales);
$stmtSales->execute();
$resultSales = $stmtSales->get_result()->fetch_assoc();
$stmtSales->close();

$taxable_sales = $resultSales['taxable_sales'] ?? 0;
$output_vat = $resultSales['output_vat'] ?? 0;

// Execute purchase VAT query
$stmtPurchases = $conn->prepare($sqlPurchases);
$stmtPurchases->bind_param($typesPurchases, ...$paramsPurchases);
$stmtPurchases->execute();
$resultPurchases = $stmtPurchases->get_result()->fetch_assoc();
$stmtPurchases->close();

$taxable_purchases = $resultPurchases['taxable_purchases'] ?? 0;
$input_vat = $resultPurchases['input_vat'] ?? 0;

// VAT Payable/Refundable
$vat_balance = $output_vat - $input_vat;
$page_title = "VAT Tax Report";


// Assume: $date_from, $date_to, $store_id, $stores, $taxable_sales, $output_vat, $taxable_purchases, $input_vat, $vat_balance already computed
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title><?= htmlspecialchars($page_title) ?></title>
    <link rel="icon" type="image/png" href="../../images/logo.png" />
    <style>
        body {
            margin: 0;
            background: url('../../images/profile.jpg') no-repeat center center fixed;
            background-size: cover;
            font-family: 'Segoe UI', sans-serif;
            color: #eee;
        }

        .content {
            margin: 2rem auto 0 auto;
            padding: 45px;
            max-width: 1850px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        h1.page-title {
            color: #ffa500;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 700;
            font-size: 2rem;
        }

        h1.page-title img {
            height: 40px;
            width: auto;
        }

        a.back-link {
            color: #ffa500;
            text-decoration: none;
            font-weight: 600;
            border: 1.5px solid #ffa500;
            padding: 6px 14px;
            border-radius: 8px;
            transition: background-color 0.3s ease, color 0.3s ease;
            white-space: nowrap;
        }

        a.back-link:hover {
            background-color: #ffa500;
            color: #222;
        }

        .filter-form {
            margin: 20px 0;
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .filter-form input, .filter-form select, .filter-form button, .filter-form a {
            padding: 10px 14px;
            border-radius: 8px;
            border: none;
            font-weight: 500;
            min-width: 160px;
        }

        .filter-form button {
            background: #ffa500;
            color: #222;
            cursor: pointer;
        }

        .filter-form a {
            background: rgba(255,255,255,0.15);
            color: #ffa500;
            text-decoration: none;
            font-weight: 500;
            display: inline-block;
            line-height: 1.5;
        }

        .filter-form a:hover {
            background: #ffa500;
            color: #222;
        }

        .card {
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            padding: 25px;
            margin-top: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 15px;
        }

        table th, table td {
            padding: 12px 20px;
            border-bottom: 1px solid rgba(255,255,255,0.2);
            vertical-align: middle;
            text-align: right;
        }

        table th {
            background: rgba(255,165,0,0.3);
            color: #fff;
            text-align: left;
        }

        .total-row {
            font-weight: bold;
            background: rgba(255,255,255,0.05);
        }

        @media print {
            .filter-form, .back-link {
                display: none;
            }
            body {
                background: #fff;
                color: #000;
            }
            table th {
                background: #eee;
                color: #000;
            }
        }
    </style>
</head>
<body>

<div class="content">

    <div class="page-header">
        <h1 class="page-title">
            <img src="../../images/logo.png" alt="Logo" />
            <?= htmlspecialchars($page_title) ?>
        </h1>
        <a href="reports_dashboard.php" class="back-link">&laquo; Back to Reports Dashboard</a>
    </div>

    <form method="get" class="filter-form">
        <input type="date" name="from_date" value="<?= htmlspecialchars($date_from) ?>" />
        <input type="date" name="to_date" value="<?= htmlspecialchars($date_to) ?>" />
        <select name="store_id">
            <option value="">All Stores</option>
            <?php foreach ($stores as $store): ?>
                <option value="<?= $store['id'] ?>" <?= $store_id == $store['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($store['store_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
        <button type="submit">Filter</button>
        <button type="button" onclick="window.print()">🖨 Print</button>
        <a href="?<?= http_build_query(array_merge($_GET, ['export' => 'csv'])) ?>">⬇ Export CSV</a>
        <a href="?<?= http_build_query(array_merge($_GET, ['export' => 'pdf'])) ?>">📄 Export PDF</a>
    </form>

    <div class="card">
        <table>
            <tbody>
                <tr>
                    <th>Taxable Sales (MWK)</th>
                    <td><?= number_format($taxable_sales, 2) ?></td>
                </tr>
                <tr>
                    <th>VAT Collected / Output VAT (MWK)</th>
                    <td><?= number_format($output_vat, 2) ?></td>
                </tr>
                <tr>
                    <th>Taxable Purchases (MWK)</th>
                    <td><?= number_format($taxable_purchases, 2) ?></td>
                </tr>
                <tr>
                    <th>VAT Paid / Input VAT (MWK)</th>
                    <td><?= number_format($input_vat, 2) ?></td>
                </tr>
                <tr class="total-row">
                    <th>VAT Payable / Refundable (MWK)</th>
                    <td><?= number_format($vat_balance, 2) ?></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<?php include('../../includes/footer.php'); ob_end_flush(); ?>
</body>
</html>