<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Access denied. Admin only.");
}

include 'config.php';
date_default_timezone_set('Asia/Colombo');

// Handle deletion if requested
if (isset($_POST['delete_sale'])) {
    $sale_id = (int)$_POST['sale_id'];
    
    // Start transaction
    mysqli_begin_transaction($conn);
    
    try {
        // Get sale items to restore stock
        $items_query = "SELECT product_id, quantity FROM sale_items WHERE sale_id = ?";
        $stmt = mysqli_prepare($conn, $items_query);
        mysqli_stmt_bind_param($stmt, "i", $sale_id);
        mysqli_stmt_execute($stmt);
        $items_result = mysqli_stmt_get_result($stmt);
        
        // Restore stock for each item
        while ($item = mysqli_fetch_assoc($items_result)) {
            $update_stock = "UPDATE products SET stock = stock + ? WHERE id = ?";
            $stock_stmt = mysqli_prepare($conn, $update_stock);
            mysqli_stmt_bind_param($stock_stmt, "ii", $item['quantity'], $item['product_id']);
            mysqli_stmt_execute($stock_stmt);
        }
        
        // Delete sale items
        $delete_items = "DELETE FROM sale_items WHERE sale_id = ?";
        $stmt = mysqli_prepare($conn, $delete_items);
        mysqli_stmt_bind_param($stmt, "i", $sale_id);
        mysqli_stmt_execute($stmt);
        
        // Delete sale
        $delete_sale = "DELETE FROM sales WHERE id = ?";
        $stmt = mysqli_prepare($conn, $delete_sale);
        mysqli_stmt_bind_param($stmt, "i", $sale_id);
        mysqli_stmt_execute($stmt);
        
        mysqli_commit($conn);
        $success_message = "Sale #$sale_id deleted successfully and stock restored.";
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error_message = "Error deleting sale: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Sales Data Cleanup - Admin Tool</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h5><i class="fas fa-tools"></i> Sales Data Cleanup Tool</h5>
                        <p class="mb-0">⚠️ Admin Only - Use with caution!</p>
                    </div>
                    <div class="card-body">
                        <?php if (isset($success_message)): ?>
                            <div class="alert alert-success"><?php echo $success_message; ?></div>
                        <?php endif; ?>
                        
                        <?php if (isset($error_message)): ?>
                            <div class="alert alert-danger"><?php echo $error_message; ?></div>
                        <?php endif; ?>

                        <!-- Current Dashboard Stats -->
                        <?php
                        $today_total_query = "SELECT COALESCE(SUM(total_amount), 0) as total, COUNT(*) as count FROM sales WHERE DATE(sale_date) = CURDATE()";
                        $today_result = mysqli_query($conn, $today_total_query);
                        $today_data = mysqli_fetch_assoc($today_result);
                        ?>
                        
                        <div class="alert alert-info">
                            <h6>Current Dashboard Shows:</h6>
                            <p class="mb-0">Today's Sales: <strong>Rs <?php echo number_format($today_data['total'], 2); ?></strong> (<?php echo $today_data['count']; ?> transactions)</p>
                        </div>

                        <!-- Today's Sales List -->
                        <h6>Today's Sales (<?php echo date('Y-m-d'); ?>):</h6>
                        
                        <?php
                        $sales_query = "SELECT s.id, s.total_amount, s.payment_method, s.sale_date, s.customer_phone,
                                               COUNT(si.id) as item_count
                                        FROM sales s 
                                        LEFT JOIN sale_items si ON s.id = si.sale_id
                                        WHERE DATE(s.sale_date) = CURDATE() 
                                        GROUP BY s.id
                                        ORDER BY s.sale_date DESC";
                        $sales_result = mysqli_query($conn, $sales_query);
                        ?>
                        
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Sale ID</th>
                                        <th>Amount</th>
                                        <th>Payment</th>
                                        <th>Time</th>
                                        <th>Phone</th>
                                        <th>Items</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($sale = mysqli_fetch_assoc($sales_result)): ?>
                                    <tr>
                                        <td>#<?php echo $sale['id']; ?></td>
                                        <td>Rs <?php echo number_format($sale['total_amount'], 2); ?></td>
                                        <td><?php echo ucfirst($sale['payment_method']); ?></td>
                                        <td><?php echo date('H:i:s', strtotime($sale['sale_date'])); ?></td>
                                        <td><?php echo $sale['customer_phone'] ?: '-'; ?></td>
                                        <td><?php echo $sale['item_count']; ?> items</td>
                                        <td>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this sale? Stock will be restored.')">
                                                <input type="hidden" name="sale_id" value="<?php echo $sale['id']; ?>">
                                                <button type="submit" name="delete_sale" class="btn btn-danger btn-sm">
                                                    <i class="fas fa-trash"></i> Delete
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                    
                                    <?php if (mysqli_num_rows($sales_result) == 0): ?>
                                    <tr>
                                        <td colspan="7" class="text-center">No sales found for today</td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Quick Actions -->
                        <div class="mt-4">
                            <h6>Quick Actions:</h6>
                            <a href="dashboard.php" class="btn btn-primary">
                                <i class="fas fa-tachometer-alt"></i> Back to Dashboard
                            </a>
                            <a href="pos/" class="btn btn-success">
                                <i class="fas fa-cash-register"></i> Make New Sale
                            </a>
                            <button onclick="location.reload()" class="btn btn-secondary">
                                <i class="fas fa-refresh"></i> Refresh Data
                            </button>
                        </div>

                        <!-- Instructions -->
                        <div class="alert alert-warning mt-4">
                            <h6><i class="fas fa-info-circle"></i> Instructions:</h6>
                            <ul class="mb-0">
                                <li>Review today's sales above</li>
                                <li>Delete any incorrect/test sales using the red delete button</li>
                                <li>Stock will be automatically restored when you delete a sale</li>
                                <li>The dashboard will update automatically after deletion</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
