<?php
session_start();
include "../config/db.php";

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

$order_id = mysqli_real_escape_string($conn, $_GET['id']);

// Get order details
$order = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT orders.*, users.name, users.email, users.phone, users.address
     FROM orders
     JOIN users ON orders.user_id = users.id
     WHERE orders.id='$order_id'"
));

if (!$order) {
    echo "Order not found";
    exit();
}

// Handle Return Finalization
if (isset($_POST['finalize_return'])) {
    $damage_cost = mysqli_real_escape_string($conn, $_POST['damage_cost']);
    $penalty_paid = mysqli_real_escape_string($conn, $_POST['penalty_amount']);
    $status = 'Returned';
    
    // Get total security deposit from order_items (captured at time of purchase)
    $deposit_res = mysqli_query($conn, "SELECT SUM(security_deposit * quantity) as total_deposit 
                                        FROM order_items 
                                        WHERE order_id = '$order_id'");
    $deposit_row = mysqli_fetch_assoc($deposit_res);
    $total_deposit = $deposit_row['total_deposit'] ?? 0;
    
    // 2. Decide: Block or Refund based on Security Deposit
    $total_deduction = (float)$damage_cost + (float)$penalty_paid;
    $refund_status = 'refunded';
    
    // Logic from Diagram: 
    // if (total costs >= security deposit) then Block User account
    // else { refund the security deposit }
    if ($total_deduction >= (float)$total_deposit && (float)$total_deposit > 0) {
        // Block User
        mysqli_query($conn, "UPDATE users SET status = 'blocked' WHERE id = '{$order['user_id']}'");
        
        // Distinguish why blocked
        if ($damage_cost > 0 && ($damage_cost + $penalty_paid) > $total_deposit) {
            $refund_status = 'blocked_damage';
            $success_msg = "Return finalized. User BLOCKED due to high damage costs exceeding security deposit.";
        } else {
            $refund_status = 'blocked_penalty';
            $success_msg = "Return finalized. User BLOCKED due to late penalties exceeding security deposit.";
        }
    } else {
        $refund_status = 'refunded';
        $remaining_refund = (float)$total_deposit - $total_deduction;
        
        // Add refund to user wallet
        if ($remaining_refund > 0) {
            mysqli_query($conn, "UPDATE users SET wallet_balance = wallet_balance + $remaining_refund WHERE id = '{$order['user_id']}'");
            $success_msg = "Return finalized. Refund of ₹" . number_format($remaining_refund, 2) . " has been added to the user's wallet.";
        } else {
            $success_msg = "Return finalized. No security deposit refund remains after deductions.";
        }
    }
    
    mysqli_query($conn, "UPDATE orders SET 
                         status = '$status', 
                         damage_cost = '$damage_cost', 
                         penalty_amount = '$penalty_paid',
                         refund_status = '$refund_status' 
                         WHERE id = '$order_id'");
    
    // Refresh order data
    $order = mysqli_fetch_assoc(mysqli_query($conn, "SELECT orders.*, users.name, users.email, users.phone, users.address FROM orders JOIN users ON orders.user_id = users.id WHERE orders.id='$order_id'"));
}

// Get order items
$items = mysqli_query($conn,
    "SELECT * FROM order_items WHERE order_id='$order_id'"
);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Details - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="../assets/css/style.css" rel="stylesheet">
    <style>
        .main-content {
            margin-left: 220px;
            padding: 30px;
            background: #f8f9fa;
            min-height: 100vh;
        }
        .order-details-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        .status-badge {
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-paid { background: #d4edda; color: #155724; }
        .status-shipped { background: #cce5ff; color: #004085; }
        .status-delivered { background: #d1ecf1; color: #0c5460; }
        .status-cancelled { background: #f8d7da; color: #721c24; }
        .status-returned { background: #f3e5f5; color: #7b1fa2; }
        .status-inuse { background: #fff4e5; color: #d9480f; }
        .status-overdue { background: #ffe3e3; color: #c92a2a; }
        .status-requested { background: #e9ecef; color: #495057; }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <?php include "includes/sidebar.php"; ?>

    <div class="main-content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 style="color: var(--dark-blue);">
                <i class="fas fa-file-invoice me-2"></i>Order Details
            </h2>
            <a href="orders.php" class="btn btn-outline-primary">
                <i class="fas fa-arrow-left me-2"></i>Back to Orders
            </a>
        </div>

        <div class="order-details-container">
            <div class="row mb-4">
                <div class="col-md-6">
                    <h4>Order #<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></h4>
                    <p class="text-muted"> Date: <?php echo date('F j, Y, h:i A', strtotime($order['created_at'])); ?> </p>
                </div>
                <div class="col-md-6 text-end">
                    <span class="status-badge <?php 
                        switch($order['status']) {
                            case 'Pending': echo 'status-pending'; break;
                            case 'Paid': echo 'status-paid'; break;
                            case 'Shipped': echo 'status-shipped'; break;
                            case 'Delivered': echo 'status-delivered'; break;
                            case 'Cancelled': echo 'status-cancelled'; break;
                            case 'Returned': echo 'status-returned'; break;
                            case 'In Use': echo 'status-inuse'; break;
                            case 'Overdue': echo 'status-overdue'; break;
                            case 'Return Requested': echo 'status-requested'; break;
                        }
                    ?>">
                        <?php echo $order['status'] ?? 'Pending'; ?>
                    </span>
                </div>
            </div>

            <?php if(isset($success_msg)): ?>
                <div class="alert alert-success alert-dismissible fade show mb-4">
                    <i class="fas fa-check-circle me-2"></i><?php echo $success_msg; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="row">
                <div class="col-md-6">
                    <div class="card mb-4">
                        <div class="card-header bg-light"> <h5 class="mb-0">Customer Information</h5> </div>
                        <div class="card-body">
                            <p class="mb-2"><strong>Name:</strong> <?php echo htmlspecialchars($order['name']); ?></p>
                            <p class="mb-2"><strong>Email:</strong> <?php echo htmlspecialchars($order['email']); ?></p>
                            <p class="mb-2"><strong>Phone:</strong> <?php echo htmlspecialchars($order['phone'] ?? 'N/A'); ?></p>
                            <p class="mb-0"><strong>Address:</strong> <?php echo htmlspecialchars($order['address']); ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card mb-4">
                        <div class="card-header bg-light"> <h5 class="mb-0">Order Summary</h5> </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr><th>Product</th><th>Qty</th><th>Price</th><th>Deposit</th><th>Total</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $subtotal = 0;
                                        $total_order_deposit = 0;
                                        mysqli_data_seek($items, 0);
                                        while($item = mysqli_fetch_assoc($items)):
                                            $item_total = $item['price'] * $item['quantity'];
                                            $item_deposit = ($item['security_deposit'] ?? 0) * $item['quantity'];
                                            $subtotal += $item_total;
                                            $total_order_deposit += $item_deposit;
                                        ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                                            <td><?php echo $item['quantity']; ?></td>
                                            <td>₹<?php echo number_format($item['price'], 2); ?></td>
                                            <td>₹<?php echo number_format($item['security_deposit'] ?? 0, 2); ?></td>
                                            <td>₹<?php echo number_format($item_total, 2); ?></td>
                                        </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr><td colspan="4" class="text-end fw-bold">Order Total:</td><td class="fw-bold">₹<?php echo number_format($order['total_price'], 2); ?></td></tr>
                                        <tr><td colspan="4" class="text-end fw-bold text-primary">Security Deposit:</td><td class="fw-bold text-primary">₹<?php echo number_format($total_order_deposit, 2); ?></td></tr>
                                        <?php if($order['penalty_amount'] > 0): ?>
                                        <tr><td colspan="4" class="text-end fw-bold text-danger">Late Penalty:</td><td class="fw-bold text-danger">+ ₹<?php echo number_format($order['penalty_amount'], 2); ?></td></tr>
                                        <?php endif; ?>
                                        <tr><td colspan="4" class="text-end h5 fw-bold">Grand Total:</td><td class="h5 fw-bold text-success">₹<?php echo number_format($order['total_price'] + $order['penalty_amount'], 2); ?></td></tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row mt-4">
                <?php if($order['pickup_scheduled_date'] || $order['status'] == 'In Use' || $order['status'] == 'Overdue' || $order['status'] == 'Return Requested'): ?>
                <div class="col-md-6">
                    <div class="card h-100">
                        <div class="card-header bg-warning bg-opacity-10"> <h5 class="mb-0 text-dark">Rental & Return Information</h5> </div>
                        <div class="card-body">
                            <p><strong>Rental Start:</strong> <?php echo date('F j, Y', strtotime($order['start_date'])); ?></p>
                            <p><strong>Rental End (Planned):</strong> <?php echo date('F j, Y', strtotime($order['return_date'])); ?></p>
                            <?php if($order['end_date']): ?>
                                <p><strong>Rental End (Actual):</strong> <?php echo date('F j, Y', strtotime($order['end_date'])); ?></p>
                            <?php endif; ?>
                            <?php if($order['pickup_scheduled_date']): ?>
                                <p class="text-primary fw-bold"><i class="fas fa-truck me-2"></i>Scheduled Pickup: <?php echo date('F j, Y', strtotime($order['pickup_scheduled_date'])); ?></p>
                            <?php endif; ?>
                            <?php if($order['penalty_amount'] > 0): ?>
                                <p class="text-danger"><strong>Late Penalty:</strong> ₹<?php echo number_format($order['penalty_amount'], 2); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <?php if(in_array($order['status'], ['In Use', 'Overdue', 'Return Requested'])): ?>
                <div class="col-md-6">
                    <div class="card h-100 border-primary">
                        <div class="card-header bg-primary text-white"> <h5 class="mb-0">Finalize Return</h5> </div>
                        <div class="card-body">
                            <form method="POST">
                                <div class="mb-3">
                                    <label class="form-label">Damage Cost (Enter 0 if none)</label>
                                    <div class="input-group">
                                        <span class="input-group-text">₹</span>
                                        <input type="number" step="0.01" name="damage_cost" class="form-control" value="0.00" required>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Penalty Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">₹</span>
                                        <input type="number" step="0.01" name="penalty_amount" class="form-control" value="<?php echo $order['penalty_amount']; ?>" required>
                                    </div>
                                </div>
                                <button type="submit" name="finalize_return" class="btn btn-primary w-100" onclick="return confirm('Finalize this return?')"> Finalize & Record Return </button>
                            </form>
                        </div>
                    </div>
                </div>
                <?php elseif($order['status'] == 'Returned'): ?>
                <div class="col-md-6">
                    <div class="card h-100 bg-light">
                        <div class="card-header bg-success text-white"> <h5 class="mb-0">Return Processed</h5> </div>
                        <div class="card-body">
                            <p><strong>Damage Cost:</strong> ₹<?php echo number_format($order['damage_cost'], 2); ?></p>
                            <p><strong>Penalty Amount:</strong> ₹<?php echo number_format($order['penalty_amount'], 2); ?></p>
                            <p><strong>Refund Status:</strong> 
                                <span class="badge <?php echo $order['refund_status'] == 'refunded' ? 'bg-success' : 'bg-danger'; ?>">
                                    <?php echo strtoupper(str_replace('_', ' ', $order['refund_status'])); ?>
                                </span>
                            </p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <div class="card mt-4">
                <div class="card-header bg-light"> <h5 class="mb-0">Order Notes</h5> </div>
                <div class="card-body">
                    <?php if(!empty($order['special_instructions'])): ?>
                        <p><?php echo nl2br(htmlspecialchars($order['special_instructions'])); ?></p>
                    <?php else: ?>
                        <p class="text-muted">No special instructions provided.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>