<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: auth-basic-signin.php");
    exit();
}

require_once __DIR__ . '/../inc/db.php';

$user_id = $_SESSION['user_id'];

// Fetch user data
$sql = "SELECT name, email, phone, mobile, address, instagram, facebook, profile_image 
        FROM users WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();

// Get date range filters
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$report_type = isset($_GET['report_type']) ? $_GET['report_type'] : 'all';

// Calculate sales statistics
$sales_stats = [
    'temporary' => ['total' => 0, 'received' => 0, 'pending' => 0, 'count' => 0],
    'permanent' => ['total' => 0, 'received' => 0, 'pending' => 0, 'count' => 0],
    'party' => ['total' => 0, 'received' => 0, 'pending' => 0, 'count' => 0]
];

// Temporary customer sales (without date filtering for now)
$temp_sql = "SELECT SUM(total_amount) as total, SUM(amount_payment) as received, COUNT(*) as count 
             FROM customer_items";
$result = $conn->query($temp_sql);
if ($result) {
    $temp_data = $result->fetch_assoc();
    if ($temp_data) {
        $sales_stats['temporary']['total'] = (float)($temp_data['total'] ?? 0);
        $sales_stats['temporary']['received'] = (float)($temp_data['received'] ?? 0);
        $sales_stats['temporary']['pending'] = $sales_stats['temporary']['total'] - $sales_stats['temporary']['received'];
        $sales_stats['temporary']['count'] = (int)($temp_data['count'] ?? 0);
    }
}

// Permanent customer sales (without date filtering for now)
$perm_sql = "SELECT SUM(total_amount) as total, SUM(amount_payment) as received, COUNT(*) as count 
             FROM permanentcustomeritem";
$result = $conn->query($perm_sql);
if ($result) {
    $perm_data = $result->fetch_assoc();
    if ($perm_data) {
        $sales_stats['permanent']['total'] = (float)($perm_data['total'] ?? 0);
        $sales_stats['permanent']['received'] = (float)($perm_data['received'] ?? 0);
        $sales_stats['permanent']['pending'] = $sales_stats['permanent']['total'] - $sales_stats['permanent']['received'];
        $sales_stats['permanent']['count'] = (int)($perm_data['count'] ?? 0);
    }
}

// Party customer sales (without date filtering for now) - No party table exists, set to 0
$sales_stats['party']['total'] = 0;
$sales_stats['party']['received'] = 0;
$sales_stats['party']['pending'] = 0;
$sales_stats['party']['count'] = 0;

// Calculate totals
$total_sales = $sales_stats['temporary']['total'] + $sales_stats['permanent']['total'] + $sales_stats['party']['total'];
$total_received = $sales_stats['temporary']['received'] + $sales_stats['permanent']['received'] + $sales_stats['party']['received'];
$total_pending = $sales_stats['temporary']['pending'] + $sales_stats['permanent']['pending'] + $sales_stats['party']['pending'];
$total_transactions = $sales_stats['temporary']['count'] + $sales_stats['permanent']['count'] + $sales_stats['party']['count'];

// Get recent transactions (simplified without date filtering)
$recent_transactions = [];
$recent_sql = "SELECT 'temporary' as type, customer_id, total_amount, amount_payment, 'Temporary Customer' as customer_type, created_at
               FROM customer_items 
               UNION ALL
               SELECT 'permanent' as type, customer_id, total_amount, amount_payment, 'Permanent Customer' as customer_type, created_at
               FROM permanentcustomeritem 
               ORDER BY created_at DESC LIMIT 20";

$result = $conn->query($recent_sql);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $recent_transactions[] = $row;
    }
}

// Get product sales data (simplified)
$product_sales = [];
$product_sql = "SELECT p.name, p.price, 
                COALESCE(SUM(ci.quantity), 0) + COALESCE(SUM(pci.quantity), 0) as total_quantity,
                COALESCE(SUM(ci.total_amount), 0) + COALESCE(SUM(pci.total_amount), 0) as total_sales
                FROM products p
                LEFT JOIN customer_items ci ON p.id = ci.product_id
                LEFT JOIN permanentcustomeritem pci ON p.id = pci.product_id
                GROUP BY p.id, p.name, p.price
                HAVING total_quantity > 0
                ORDER BY total_sales DESC
                LIMIT 10";

$result = $conn->query($product_sql);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $product_sales[] = $row;
    }
}
?>

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--favicon-->
    <link rel="icon" href="assets/images/logo-icon.png" type="image/png" />
    <!--plugins-->
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <link href="assets/plugins/datatable/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <!-- loader-->
    <link href="assets/css/pace.min.css" rel="stylesheet" />
    <script src="assets/js/pace.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <link href="assets/css/app.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    
    <title>Sell & Purchase Reports - Kumawat Computer</title>
</head>

<body class="bg-theme bg-theme2">
    <!--wrapper-->
    <div class="wrapper">
        <!--sidebar wrapper -->
        <div class="sidebar-wrapper" data-simplebar="true">
            <div class="sidebar-header">
                <div>
                    <img src="assets/images/logo-icon.png" class="logo-icon" alt="logo icon">
                </div>
                <div>
                    <h4 class="logo-text">Kumawat</h4>
                </div>
                <div class="toggle-icon ms-auto"><i class='bx bx-arrow-back'></i>
                </div>
             </div>
            <!--navigation-->
            <ul class="metismenu" id="menu">
                <li>
                    <a href="index.php">
                        <div class="parent-icon"><i class='bx bx-home-alt'></i>
                        </div>
                        <div class="menu-title">Home</div>
                    </a> 
                </li>  
                <li>
                    <a href="table-datatable.php">
                        <div class="parent-icon"><i class="bx bx-grid-alt"></i>
                        </div>
                        <div class="menu-title">Product Tables</div>
                    </a> 
                </li>
              
                <li>
                    <a href="ecommerce-products.php">
                        <div class="parent-icon"><i class='bx bx-briefcase-alt'></i>
                        </div>
                        <div class="menu-title">Products</div>
                    </a> 
                </li>  
                <li>
                    <a href="ecommerce-add-new-products.php">
                        <div class="parent-icon"><i class='bx bx-store'></i>
                        </div>
                        <div class="menu-title">Add New Products</div>
                    </a> 
                </li> 
                <li>
                    <a href="temprary.php">
                        <div class="parent-icon"><i class='bx bx-repeat'></i>
                        </div>
                        <div class="menu-title">Temporary</div>
                    </a> 
                </li> 
                <li>
                    <a href="permanent-customer.php">
                        <div class="parent-icon"><i class='bx bx-bookmark-heart'></i>
                        </div>
                        <div class="menu-title">Permanent Customer</div>
                    </a> 
                </li>
                <li>
                    <a href="party-customer.php">
                        <div class="parent-icon"><i class='bx bx-cookie'></i>
                        </div>
                        <div class="menu-title">Party</div>
                    </a> 
                </li>
                <li>
                    <a href="sell-purchase-selection.php">
                        <div class="parent-icon"><i class='bx bx-transfer'></i>
                        </div>
                        <div class="menu-title">Sell & Purchase</div>
                    </a> 
                </li>
                <li>
                    <a href="sell-purchase-reports.php" class="mm-active">
                        <div class="parent-icon"><i class='bx bx-bar-chart-alt-2'></i>
                        </div>
                        <div class="menu-title">Sell & Purchase Reports</div>
                    </a> 
                </li>
                <li>
                    <a href="ecommerce-orders.php">
                        <div class="parent-icon"><i class='bx bx-cart'></i>
                        </div>
                        <div class="menu-title">History</div>
                    </a> 
                </li> 
                <li>
                    <a href="user-profile.php">
                        <div class="parent-icon"><i class="bx bx-user-circle"></i>
                        </div>
                        <div class="menu-title">User Profile</div>
                    </a>
                </li>  
            </ul>
            <!--end navigation-->
        </div>
        <!--end sidebar wrapper -->
        <!--start header -->
        <header>
            <div class="topbar d-flex align-items-center">
                <nav class="navbar navbar-expand gap-3">
                    <div class="mobile-toggle-menu"><i class='bx bx-menu'></i>
                    </div>
                    <div class="search-bar flex-grow-1">
                        <div class="position-relative search-bar-box">
                            <input type="text" class="form-control search-control" placeholder="Type to search..."> <span class="position-absolute top-50 search-show translate-middle-y"><i class='bx bx-search'></i></span>
                            <span class="position-absolute top-50 search-close translate-middle-y"><i class='bx bx-x'></i></span>
                        </div>
                    </div>
                    <div class="top-menu ms-auto">
                        <ul class="navbar-nav align-items-center gap-1">
                            <li class="nav-item mobile-search-icon d-flex d-lg-none" data-bs-toggle="modal" data-bs-target="#SearchModal">
                                <a class="nav-link" href="avascript:;"><i class='bx bx-search'></i>
                                </a>
                            </li>  
                        </ul>
                    </div>
                    <div class="user-box dropdown px-3">
                        <a class="d-flex align-items-center nav-link dropdown-toggle gap-3 dropdown-toggle-nocaret" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <img src="<?= htmlspecialchars($user['profile_image'] ?: 'assets/images/avatars/avatar-2.png') ?>"
                                             alt="Profile" class="user-img">
                            <div class="user-info">
                                <p class="user-name mb-0"><?= htmlspecialchars($user['name']) ?></p>
                                <p class="designattion mb-0"><?= htmlspecialchars($user['email']) ?></p>
                            </div>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item d-flex align-items-center" href="user-profile.php"><i class="bx bx-user fs-5"></i><span>Profile</span></a>
                            </li> 
                            <li>
                                <div class="dropdown-divider mb-0"></div>
                            </li>
                            <li><a class="dropdown-item d-flex align-items-center" href="logout.php"><i class="bx bx-log-out-circle"></i><span>Logout</span></a>
                            </li>
                        </ul>
                    </div>
                </nav>
            </div>
        </header>
        <!--end header -->
        <!--start page wrapper -->
        <div class="page-wrapper">
            <div class="page-content">
                <!-- Filter Section -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Sell & Purchase Reports</h4>
                                <form method="GET" class="row g-3">
                                    <div class="col-md-3">
                                        <label class="form-label">Start Date</label>
                                        <input type="date" class="form-control" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">End Date</label>
                                        <input type="date" class="form-control" name="end_date" value="<?= htmlspecialchars($end_date) ?>">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Report Type</label>
                                        <select class="form-select" name="report_type">
                                            <option value="all" <?= $report_type == 'all' ? 'selected' : '' ?>>All Reports</option>
                                            <option value="sales" <?= $report_type == 'sales' ? 'selected' : '' ?>>Sales Only</option>
                                            <option value="purchase" <?= $report_type == 'purchase' ? 'selected' : '' ?>>Purchase Only</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">&nbsp;</label>
                                        <div>
                                            <button type="submit" class="btn btn-primary">Filter</button>
                                            <a href="sell-purchase-reports.php" class="btn btn-secondary">Reset</a>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Summary Cards -->
                <div class="row">
                    <div class="col-md-3">
                        <div class="card border-primary">
                            <div class="card-body">
                                <div class="d-flex align-items-center">
                                    <div>
                                        <h4 class="mb-0">₹<?= number_format($total_sales, 2) ?></h4>
                                        <p class="mb-0">Total Sales</p>
                                    </div>
                                    <div class="widgets-icons ms-auto"><i class='bx bx-trending-up text-primary'></i></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card border-success">
                            <div class="card-body">
                                <div class="d-flex align-items-center">
                                    <div>
                                        <h4 class="mb-0">₹<?= number_format($total_received, 2) ?></h4>
                                        <p class="mb-0">Amount Received</p>
                                    </div>
                                    <div class="widgets-icons ms-auto"><i class='bx bx-check-circle text-success'></i></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card border-warning">
                            <div class="card-body">
                                <div class="d-flex align-items-center">
                                    <div>
                                        <h4 class="mb-0">₹<?= number_format($total_pending, 2) ?></h4>
                                        <p class="mb-0">Pending Amount</p>
                                    </div>
                                    <div class="widgets-icons ms-auto"><i class='bx bx-time text-warning'></i></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card border-info">
                            <div class="card-body">
                                <div class="d-flex align-items-center">
                                    <div>
                                        <h4 class="mb-0"><?= $total_transactions ?></h4>
                                        <p class="mb-0">Total Transactions</p>
                                    </div>
                                    <div class="widgets-icons ms-auto"><i class='bx bx-receipt text-info'></i></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Detailed Statistics -->
                <div class="row">
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Temporary Customer Sales</h5>
                            </div>
                            <div class="card-body">
                                <div class="row text-center">
                                    <div class="col-4">
                                        <h6 class="text-primary">₹<?= number_format($sales_stats['temporary']['total'], 2) ?></h6>
                                        <small class="text-muted">Total</small>
                                    </div>
                                    <div class="col-4">
                                        <h6 class="text-success">₹<?= number_format($sales_stats['temporary']['received'], 2) ?></h6>
                                        <small class="text-muted">Received</small>
                                    </div>
                                    <div class="col-4">
                                        <h6 class="text-warning">₹<?= number_format($sales_stats['temporary']['pending'], 2) ?></h6>
                                        <small class="text-muted">Pending</small>
                                    </div>
                                </div>
                                <hr>
                                <div class="text-center">
                                    <h6 class="text-info"><?= $sales_stats['temporary']['count'] ?></h6>
                                    <small class="text-muted">Transactions</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Permanent Customer Sales</h5>
                            </div>
                            <div class="card-body">
                                <div class="row text-center">
                                    <div class="col-4">
                                        <h6 class="text-primary">₹<?= number_format($sales_stats['permanent']['total'], 2) ?></h6>
                                        <small class="text-muted">Total</small>
                                    </div>
                                    <div class="col-4">
                                        <h6 class="text-success">₹<?= number_format($sales_stats['permanent']['received'], 2) ?></h6>
                                        <small class="text-muted">Received</small>
                                    </div>
                                    <div class="col-4">
                                        <h6 class="text-warning">₹<?= number_format($sales_stats['permanent']['pending'], 2) ?></h6>
                                        <small class="text-muted">Pending</small>
                                    </div>
                                </div>
                                <hr>
                                <div class="text-center">
                                    <h6 class="text-info"><?= $sales_stats['permanent']['count'] ?></h6>
                                    <small class="text-muted">Transactions</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Party Customer Sales</h5>
                            </div>
                            <div class="card-body">
                                <div class="row text-center">
                                    <div class="col-4">
                                        <h6 class="text-primary">₹<?= number_format($sales_stats['party']['total'], 2) ?></h6>
                                        <small class="text-muted">Total</small>
                                    </div>
                                    <div class="col-4">
                                        <h6 class="text-success">₹<?= number_format($sales_stats['party']['received'], 2) ?></h6>
                                        <small class="text-muted">Received</small>
                                    </div>
                                    <div class="col-4">
                                        <h6 class="text-warning">₹<?= number_format($sales_stats['party']['pending'], 2) ?></h6>
                                        <small class="text-muted">Pending</small>
                                    </div>
                                </div>
                                <hr>
                                <div class="text-center">
                                    <h6 class="text-info"><?= $sales_stats['party']['count'] ?></h6>
                                    <small class="text-muted">Transactions</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Transactions -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Recent Transactions</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Type</th>
                                                <th>Customer ID</th>
                                                <th>Total Amount</th>
                                                <th>Received</th>
                                                <th>Pending</th>
                                                <th>Date</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recent_transactions as $transaction): ?>
                                            <tr>
                                                <td>
                                                    <span class="badge bg-<?= $transaction['type'] == 'temporary' ? 'primary' : ($transaction['type'] == 'permanent' ? 'success' : 'warning') ?>">
                                                        <?= htmlspecialchars($transaction['customer_type']) ?>
                                                    </span>
                                                </td>
                                                <td><?= htmlspecialchars($transaction['customer_id']) ?></td>
                                                <td>₹<?= number_format($transaction['total_amount'], 2) ?></td>
                                                <td>₹<?= number_format($transaction['amount_payment'], 2) ?></td>
                                                <td>₹<?= number_format($transaction['total_amount'] - $transaction['amount_payment'], 2) ?></td>
                                                <td><?= isset($transaction['created_at']) ? date('d M Y', strtotime($transaction['created_at'])) : date('d M Y') ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Top Selling Products -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Top Selling Products</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Product Name</th>
                                                <th>Price</th>
                                                <th>Quantity Sold</th>
                                                <th>Total Sales</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($product_sales as $product): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($product['name']) ?></td>
                                                <td>₹<?= number_format($product['price'], 2) ?></td>
                                                <td><?= $product['total_quantity'] ?></td>
                                                <td>₹<?= number_format($product['total_sales'], 2) ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--end page wrapper -->
        <!--start overlay-->
        <div class="overlay toggle-icon"></div>
        <!--end overlay-->
        <!--Start Back To Top Button--> <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
        <!--End Back To Top Button-->
        <footer class="page-footer">
            <p class="mb-0">Copyright © 2021. All right reserved.</p>
        </footer>
    </div>
    <!--end wrapper-->
    <!--start switcher-->
    <div class="switcher-wrapper">
        <div class="switcher-btn"> <i class='bx bx-cog bx-spin'></i>
        </div>
        <div class="switcher-body">
            <div class="d-flex align-items-center">
                <h5 class="mb-0 text-uppercase">Theme Customizer</h5>
                <button type="button" class="btn-close ms-auto close-switcher" aria-label="Close"></button>
            </div>
            <hr/>
            <p class="mb-0">Gaussian Texture</p>
            <hr>
            <ul class="switcher">
                <li id="theme1"></li>
                <li id="theme2"></li>
                <li id="theme3"></li>
                <li id="theme4"></li>
                <li id="theme5"></li>
                <li id="theme6"></li>
            </ul>
            <hr>
            <p class="mb-0">Gradient Background</p>
            <hr>
            <ul class="switcher">
                <li id="theme7"></li>
                <li id="theme8"></li>
                <li id="theme9"></li>
                <li id="theme10"></li>
                <li id="theme11"></li>
                <li id="theme12"></li>
                <li id="theme13"></li>
                <li id="theme14"></li>
                <li id="theme15"></li>
              </ul>
        </div>
    </div>
    <!--end switcher-->
    <!-- Bootstrap JS -->
    <script src="assets/js/bootstrap.bundle.min.js"></script>
    <!--plugins-->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
    <script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
    <script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
    <script src="assets/plugins/apexcharts-bundle/js/apexcharts.min.js"></script>
    <script src="assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
    <script src="assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/js/index.js"></script>
    <!--app JS-->
    <script src="assets/js/app.js"></script>
</body>
</html>
