<?php
// admin/add-delivery-report.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Get order_id from URL
$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
$prefilled_data = [];

if ($order_id > 0) {
    $stmt = $pdo->prepare("SELECT id, invoice_no, name, phone, address, city, total FROM orders WHERE id = ?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();
    if ($order) {
        $prefilled_data = [
            'order_id' => $order['id'],
            'invoice_no' => $order['invoice_no'],
            'customer_name' => $order['name'],
            'customer_phone' => $order['phone'],
            'customer_address' => $order['address'],
            'area' => $order['city'],
            'cod_amount' => $order['total']
        ];
    }
}

// Get pending orders for delivery
$stmt = $pdo->query("SELECT o.id, o.invoice_no, o.name, o.phone, o.address, o.total 
                     FROM orders o 
                     LEFT JOIN delivery_reports dr ON o.id = dr.order_id 
                     WHERE dr.id IS NULL AND o.order_status IN ('pending', 'processing', 'shipped', 'delivered')
                     ORDER BY o.created_at DESC");
$orders = $stmt->fetchAll();

// Get delivery agents
$agents = $pdo->query("SELECT * FROM delivery_agents WHERE status = 1 ORDER BY name")->fetchAll();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = isset($_POST['order_id']) && !empty($_POST['order_id']) ? intval($_POST['order_id']) : null;
    $customer_name = sanitize($_POST['customer_name'] ?? '');
    $customer_phone = sanitize($_POST['customer_phone'] ?? '');
    $customer_address = sanitize($_POST['customer_address'] ?? '');
    $area = sanitize($_POST['area'] ?? '');
    $delivery_agent = sanitize($_POST['delivery_agent'] ?? '');
    $delivery_status = sanitize($_POST['delivery_status'] ?? 'pending');
    $delivery_charge = floatval($_POST['delivery_charge'] ?? 0);
    $cod_amount = floatval($_POST['cod_amount'] ?? 0);
    $delivery_date = $_POST['delivery_date'] ?? date('Y-m-d');
    $note = sanitize($_POST['note'] ?? '');
    
    if (empty($customer_name) || empty($customer_phone) || empty($customer_address)) {
        $error = 'Customer name, phone, and address are required';
    } else {
        $report_no = 'DLV-' . date('Ymd') . '-' . rand(1000, 9999);
        
        $stmt = $pdo->prepare("INSERT INTO delivery_reports 
            (report_no, order_id, invoice_no, customer_name, customer_phone, customer_address, area,
             delivery_agent, delivery_status, delivery_charge, cod_amount, delivery_date, note, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        // Get invoice_no if order exists
        $invoice_no = null;
        if ($order_id) {
            $stmt2 = $pdo->prepare("SELECT invoice_no FROM orders WHERE id = ?");
            $stmt2->execute([$order_id]);
            $order = $stmt2->fetch();
            $invoice_no = $order ? $order['invoice_no'] : null;
        }
        
        $stmt->execute([
            $report_no, $order_id, $invoice_no, $customer_name, $customer_phone, $customer_address, $area,
            $delivery_agent, $delivery_status, $delivery_charge, $cod_amount, $delivery_date, $note, $_SESSION['admin_id']
        ]);
        
        $_SESSION['success_msg'] = 'Delivery report created successfully!';
        header('Location: delivery-reports.php');
        exit;
    }
}

include 'header.php';
?>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-plus-circle me-2"></i> Add Delivery Report</h2>
        <a href="delivery-reports.php" class="btn btn-secondary">
            <i class="fa-solid fa-arrow-left"></i> Back
        </a>
    </div>
    
    <?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="admin-card">
        <form method="POST">
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Order</label>
                        <select name="order_id" id="orderSelect" class="form-control">
                            <option value="">Select Order</option>
                            <?php foreach ($orders as $order): ?>
                            <option value="<?php echo $order['id']; ?>"
                                    data-name="<?php echo $order['name']; ?>"
                                    data-phone="<?php echo $order['phone']; ?>"
                                    data-address="<?php echo $order['address']; ?>"
                                    data-total="<?php echo $order['total']; ?>"
                                    <?php echo ($prefilled_data['order_id'] ?? 0) == $order['id'] ? 'selected' : ''; ?>>
                                <?php echo $order['invoice_no']; ?> - <?php echo $order['name']; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Name *</label>
                        <input type="text" name="customer_name" id="customerName" class="form-control" 
                               value="<?php echo $prefilled_data['customer_name'] ?? ''; ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Phone *</label>
                        <input type="text" name="customer_phone" id="customerPhone" class="form-control" 
                               value="<?php echo $prefilled_data['customer_phone'] ?? ''; ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Customer Address *</label>
                        <textarea name="customer_address" id="customerAddress" class="form-control" rows="2" required><?php echo $prefilled_data['customer_address'] ?? ''; ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Area</label>
                        <input type="text" name="area" class="form-control" value="<?php echo $prefilled_data['area'] ?? ''; ?>">
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Delivery Agent</label>
                        <select name="delivery_agent" class="form-control">
                            <option value="">Select Agent</option>
                            <?php foreach ($agents as $agent): ?>
                            <option value="<?php echo $agent['name']; ?>"><?php echo $agent['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Delivery Status</label>
                        <select name="delivery_status" class="form-control">
                            <option value="pending">Pending</option>
                            <option value="assigned">Assigned</option>
                            <option value="picked">Picked</option>
                            <option value="in_transit">In Transit</option>
                            <option value="delivered">Delivered</option>
                            <option value="returned">Returned</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Delivery Charge</label>
                        <input type="number" name="delivery_charge" class="form-control" step="0.01" value="0">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">COD Amount</label>
                        <input type="number" name="cod_amount" class="form-control" step="0.01" id="codAmount" 
                               value="<?php echo $prefilled_data['cod_amount'] ?? 0; ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Delivery Date</label>
                        <input type="date" name="delivery_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2"></textarea>
                    </div>
                </div>
            </div>
            
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="fa-solid fa-save"></i> Create Delivery Report
                </button>
                <a href="delivery-reports.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('orderSelect').addEventListener('change', function() {
    var selected = this.options[this.selectedIndex];
    if (selected.value) {
        document.getElementById('customerName').value = selected.getAttribute('data-name') || '';
        document.getElementById('customerPhone').value = selected.getAttribute('data-phone') || '';
        document.getElementById('customerAddress').value = selected.getAttribute('data-address') || '';
        document.getElementById('codAmount').value = selected.getAttribute('data-total') || 0;
    }
});
</script>

<?php include 'footer.php'; ?>