<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

if (isset($_POST['generate_report'])) {
    // Database connection details
    include 'connect.php';

    // Retrieve start and end dates
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];

    // Validate date range
    if ($start_date > $end_date) {
        $error_message = "<div class='alert alert-warning'>Start date cannot be later than end date.</div>";
    } else {
        // Initialize totals
        $total_purchases = 0;
        $total_sales = 0;

        // Calculate total purchases (cost of sold products)
        $sql_purchases = "SELECT SUM(sell.quantity_sold * products_table.pr_Cost) AS total_purchases
                          FROM sell
                          INNER JOIN products_table ON sell.product_number = products_table.product_number
                          WHERE sell.sell_time BETWEEN '$start_date' AND '$end_date'";

        $result_purchases = mysqli_query($conn, $sql_purchases);
        if ($result_purchases) {
            $row = mysqli_fetch_assoc($result_purchases);
            $total_purchases = $row['total_purchases'] ?? 0;
        }

        // Calculate total sales
        $sql_sales = "SELECT SUM(total_amount) AS total_sales FROM sell WHERE sell_time BETWEEN '$start_date' AND '$end_date'";
        $result_sales = mysqli_query($conn, $sql_sales);
        if ($result_sales) {
            $row = mysqli_fetch_assoc($result_sales);
            $total_sales = $row['total_sales'] ?? 0;
        }

        // Calculate profit or loss
        $profit_or_loss = $total_sales - $total_purchases;

        // Generate profit/loss message
        if ($profit_or_loss > 0) {
            $message = "<div class='alert alert-success'><strong>Profit: Tshs. " . number_format($profit_or_loss, 2) . "</strong></div>";
        } else {
            $message = "<div class='alert alert-danger'><strong>Loss: Tshs. " . number_format(abs($profit_or_loss), 2) . "</strong></div>";
        }
    }

    mysqli_close($conn);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profit Report Generator</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h2 class="mb-4">Profit Report Generator</h2>

        <form action="" method="POST" class="bg-light p-4 rounded shadow-sm">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="start_date" class="form-label">Start Date:</label>
                    <input type="date" class="form-control" id="start_date" name="start_date" required value="<?php echo date('Y-m-01'); ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="end_date" class="form-label">End Date:</label>
                    <input type="date" class="form-control" id="end_date" name="end_date" required value="<?php echo date('Y-m-d'); ?>">
                </div>
            </div>
            <button type="submit" name="generate_report" class="btn btn-primary">Generate Report</button>
        </form>

        <?php if (isset($error_message)) echo $error_message; ?>
        <?php if (isset($message)) echo $message; ?>

        <?php if (isset($_POST['generate_report']) && !isset($error_message)): ?>
        <div class="mt-4">
            <h4>Report Summary (<?php echo $start_date; ?> to <?php echo $end_date; ?>)</h4>
            <table class="table table-bordered">
                <thead class="table-dark">
                    <tr>
                        <th>Description</th>
                        <th>Amount (Tshs.)</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>Total Purchases (Cost of Sold Products)</strong></td>
                        <td><?php echo number_format($total_purchases, 2); ?></td>
                    </tr>
                    <tr>
                        <td><strong>Total Sales</strong></td>
                        <td><?php echo number_format($total_sales, 2); ?></td>
                    </tr>
                    <tr class="<?php echo ($profit_or_loss > 0) ? 'table-success' : 'table-danger'; ?>">
                        <td><strong><?php echo ($profit_or_loss > 0) ? 'Profit' : 'Loss'; ?></strong></td>
                        <td><strong><?php echo number_format(abs($profit_or_loss), 2); ?></strong></td>
                    </tr>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
