<?php
session_start();
include_once('../includes/config.php');

// Ensure PDO connection available
if (!isset($dbh) || !$dbh) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database connection (PDO) not available']);
    exit();
}

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Force JSON output
header('Content-Type: application/json');
ini_set('display_errors', 0);
error_reporting(E_ALL);

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['sale_id'])) {
        throw new Exception('Sale ID is required');
    }
    
    $saleId = (int)$input['sale_id'];
    $userId = $_SESSION['uid'];
    $deleteReason = isset($input['reason']) ? $input['reason'] : 'Sale deletion';
    
    // Start transaction
    $dbh->beginTransaction();
    
    try {
        // First, get the sale details
        $saleQuery = "
            SELECT ps.*, c.CustomerName 
            FROM tblpossales ps 
            LEFT JOIN tblcustomers c ON ps.CustomerID = c.ID 
            WHERE ps.ID = ?
        ";
        $stmt = $dbh->prepare($saleQuery);
        $stmt->execute([$saleId]);
        $sale = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$sale) {
            throw new Exception('Sale not found');
        }
        
        // Get sale items to restore stock
        $itemsQuery = "SELECT * FROM tblpossaleitems WHERE SaleID = ?";
        $stmt = $dbh->prepare($itemsQuery);
        $stmt->execute([$saleId]);
        $saleItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Restore stock for each item
        foreach ($saleItems as $item) {
            $productId = $item['ProductID'];
            $quantity = $item['Quantity'];
            
            // Get current stock
            $stockQuery = "SELECT CurrentStock FROM tblricebags WHERE ID = ?";
            $stmt = $dbh->prepare($stockQuery);
            $stmt->execute([$productId]);
            $product = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($product) {
                $currentStock = $product['CurrentStock'];
                $newStock = $currentStock + $quantity;
                
                // Update stock
                $updateStockQuery = "UPDATE tblricebags SET CurrentStock = ? WHERE ID = ?";
                $stmt = $dbh->prepare($updateStockQuery);
                $stmt->execute([$newStock, $productId]);
                
                // Create stock adjustment record for restoration
                $adjustmentQuery = "
                    INSERT INTO tblstockadjustments 
                    (RiceBagID, AdjustmentType, Quantity, PreviousStock, NewStock, Reason, 
                     ReferenceNumber, AdjustmentDate, Status, CreatedBy, CreatedDate) 
                    VALUES 
                    (?, 'Add', ?, ?, ?, ?, ?, ?, 'Approved', ?, NOW())
                ";
                
                $stmt = $dbh->prepare($adjustmentQuery);
                $stmt->execute([
                    $productId, $quantity, $currentStock, $newStock, 
                    'Sale Deletion - ' . $deleteReason, 
                    'DEL-' . $sale['SaleNumber'], 
                    date('Y-m-d'), $userId
                ]);
            }
        }
        
        // Log the deletion to audit table BEFORE deleting records
        $logQuery = "
            INSERT INTO tblauditlog 
            (TableName, RecordID, Action, Description, UserID, IPAddress, CreatedAt) 
            VALUES 
            ('tblpossales', ?, 'DELETE', ?, ?, ?, NOW())
        ";
        
        $userIP = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        $logDescription = 'PERMANENT SALE DELETION: ' . $sale['SaleNumber'] . ' - Total: ₹' . $sale['TotalAmount'] . ' - Customer: ' . $sale['CustomerName'] . ' - Reason: ' . $deleteReason;
        
        $stmt = $dbh->prepare($logQuery);
        $stmt->execute([$saleId, $logDescription, $userId, $userIP]);
        
        // Delete related customer payment records permanently
        $deleteCustomerPaymentsQuery = "
            DELETE FROM tblcustomerpayments 
            WHERE ReferenceNumber = ? OR Description LIKE ?
        ";
        $stmt = $dbh->prepare($deleteCustomerPaymentsQuery);
        $stmt->execute([$sale['SaleNumber'], '%' . $sale['SaleNumber'] . '%']);
        
        // Delete related payments from tblpospayments (will be deleted automatically by CASCADE)
        // No need to explicitly delete as CASCADE will handle it
        
        // Delete sale items (will be deleted automatically by CASCADE)
        // No need to explicitly delete as CASCADE will handle it
        
        // Finally, delete the main sale record (this will cascade delete all related records)
        $deleteSaleQuery = "DELETE FROM tblpossales WHERE ID = ?";
        $stmt = $dbh->prepare($deleteSaleQuery);
        $stmt->execute([$saleId]);
        
        // Commit transaction
        $dbh->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Sale permanently deleted successfully. Stock has been restored.',
            'data' => [
                'sale_number' => $sale['SaleNumber'],
                'total_amount' => $sale['TotalAmount'],
                'items_restored' => count($saleItems),
                'customer_name' => $sale['CustomerName'],
                'deletion_time' => date('Y-m-d H:i:s')
            ]
        ]);
        
    } catch (Exception $e) {
        $dbh->rollBack();
        throw $e;
    }
    
} catch (PDOException $e) {
    if (isset($dbh) && $dbh->inTransaction()) {
        $dbh->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'error' => $e->getCode()
    ]);
} catch (Exception $e) {
    if (isset($dbh) && $dbh->inTransaction()) {
        $dbh->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'error' => 'GENERAL'
    ]);
}
?>
