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

include('../../includes/config.php');
include('../../includes/header.php');

$from_date = $_GET['from_date'] ?? date('Y-m-01');
$to_date = $_GET['to_date'] ?? date('Y-m-d');

$categories = [
    'Operating Activities' => ['sale_income', 'deposit', 'withdrawal', 'expense', 'cogs', 'supplier_payment'],
    'Investing Activities' => ['loan'],
    'Financing Activities' => ['repayment', 'transfer']
];

$results = [];
$grand_in = 0;
$grand_out = 0;

foreach ($categories as $category => $types) {
    $placeholders = implode(',', array_fill(0, count($types), '?'));
    $params = array_merge([$from_date, $to_date], $types);
    $types_str = str_repeat('s', count($types));

    $sql = "
        SELECT ft.type, 
               SUM(ft.debit) AS total_out,
               SUM(ft.credit) AS total_in
        FROM financial_transactions ft
        WHERE ft.transaction_date BETWEEN ? AND ? 
          AND ft.type IN ($placeholders) 
          AND ft.status = 'approved'
        GROUP BY ft.type
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ss' . $types_str, ...$params);
    $stmt->execute();
    $res = $stmt->get_result();

    $data = [];
    $cat_in = 0;
    $cat_out = 0;

    while ($row = $res->fetch_assoc()) {
        $data[] = $row;
        $cat_in += $row['total_in'];
        $cat_out += $row['total_out'];
    }

    $results[$category] = [
        'data' => $data,
        'total_in' => $cat_in,
        'total_out' => $cat_out
    ];

    $grand_in += $cat_in;
    $grand_out += $cat_out;

    $stmt->close();
}

$net_cash = $grand_in - $grand_out;


$page_title = "Cash Flow Statement";
?>

<!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;
    }

    .wrap {
        max-width: 1850px;
        margin: 40px auto;
        padding: 40 20px;
    }

    .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;
    }

    h2 {
        color: #ffa500;
        margin-bottom: 20px;
    }

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

    .filters input, .filters button, .filters a {
        padding: 8px 12px;
        border-radius: 8px;
        border: none;
        font-weight: 500;
        background: rgba(255, 255, 255, 0.15);
        color: #fff;
        text-decoration: none;
    }

    .filters button {
        background: #ffa500;
        color: #222;
        cursor: pointer;
    }

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

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

    table th, table td {
        padding: 10px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    }

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

    td:nth-child(2), td:nth-child(3), td:nth-child(4),
    th:nth-child(2), th:nth-child(3), th:nth-child(4) {
        text-align: right;
    }

    a.drill-link {
        color: #ffa500;
        text-decoration: none;
        font-weight: bold;
    }

    .summary-box {
        margin-top: 20px;
        padding: 15px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 10px;
        font-size: 16px;
        font-weight: bold;
    }
    </style>
</head>
<body>

<div class="wrap">
    <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 class="filters" method="GET">
        <input type="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>">
        <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>">
        <button type="submit">Filter</button>
        <a href="?from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&export=csv">Export CSV</a>
        <a href="?from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>&export=pdf">Export PDF</a>
    </form>

    <?php foreach ($results as $category => $info): ?>
        <div class="card">
            <h3><?= htmlspecialchars($category) ?></h3>
            <table>
                <thead>
                    <tr>
                        <th>Transaction Type</th>
                        <th>Inflows</th>
                        <th>Outflows</th>
                        <th>Net</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($info['data'] as $row): 
                    $net = $row['total_in'] - $row['total_out'];
                ?>
                    <tr>
                        <td>
                            <a class="drill-link" href="cash_flow_detail.php?type=<?= urlencode($row['type']) ?>&from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>">
                                <?= ucwords(str_replace('_', ' ', $row['type'])) ?>
                            </a>
                        </td>
                        <td><?= number_format($row['total_in'], 2) ?></td>
                        <td><?= number_format($row['total_out'], 2) ?></td>
                        <td><?= number_format($net, 2) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr style="font-weight:bold;">
                        <td>Total <?= htmlspecialchars($category) ?></td>
                        <td><?= number_format($info['total_in'], 2) ?></td>
                        <td><?= number_format($info['total_out'], 2) ?></td>
                        <td><?= number_format($info['total_in'] - $info['total_out'], 2) ?></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    <?php endforeach; ?>

    <div class="summary-box">
        Net Cash Flow: <?= number_format($net_cash, 2) ?>
    </div>
</div>

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