<?php
/**
 * ADMIN ORDER STATUS UPDATE PAGE
 * File: admin/order-update-status.php
 * Update order status (confirm, complete, cancel)
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

// Get order ID and new status
$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$new_status = $_GET['status'] ?? '';

if (!$order_id || empty($new_status)) {
    flash('error', 'Invalid request', 'danger');
    redirect('orders.php');
}

// Validate status
$valid_statuses = ['confirmed', 'completed', 'cancelled'];
if (!in_array($new_status, $valid_statuses)) {
    flash('error', 'Invalid status', 'danger');
    redirect('orders.php');
}

// Initialize models
$order_model = new Order();

// Get order details
$order = $order_model->find($order_id);

if (!$order) {
    flash('error', 'Order not found', 'danger');
    redirect('orders.php');
}

// Check if status change is valid
if ($order['status'] === $new_status) {
    flash('warning', 'Order is already in this status', 'warning');
    redirect('order-details.php?id=' . $order_id);
}

// Prevent invalid status changes
if ($order['status'] === 'completed' && $new_status !== 'cancelled') {
    flash('error', 'Cannot change status of completed order', 'danger');
    redirect('order-details.php?id=' . $order_id);
}

if ($order['status'] === 'cancelled' && $new_status !== 'confirmed') {
    flash('error', 'Cannot change status of cancelled order', 'danger');
    redirect('order-details.php?id=' . $order_id);
}

// Handle status update
try {
    $admin_id = Auth::id();
    $result = $order_model->updateStatus($order_id, $new_status, $admin_id);
    
    if ($result) {
        // Update specific timestamps
        $db = Database::getInstance();
        if ($new_status === 'confirmed') {
            $db->execute("UPDATE orders SET confirmed_at = NOW() WHERE id = ?", [$order_id]);
        } elseif ($new_status === 'completed') {
            $db->execute("UPDATE orders SET completed_at = NOW() WHERE id = ?", [$order_id]);
        }
        
        // Send notification to customer
        $notification = new NotificationService();
        $status_messages = [
            'confirmed' => 'Your order has been confirmed and is ready for pickup.',
            'completed' => 'Your order has been completed. Thank you for using our service!',
            'cancelled' => 'Your order has been cancelled. If you have questions, please contact support.'
        ];
        
        $customer_model = new Customer();
        $customer = $customer_model->find($order['customer_id']);
        if ($customer) {
            $notification->send(
                $customer['user_id'],
                'Order Status Updated',
                $status_messages[$new_status],
                $new_status === 'cancelled' ? 'warning' : 'success',
                'order',
                '/customer/orders.php'
            );
        }
        
        flash('success', 'Order status updated successfully', 'success');
    } else {
        flash('error', 'Failed to update order status', 'danger');
    }
} catch (Exception $e) {
    flash('error', 'An error occurred: ' . $e->getMessage(), 'danger');
}

// Redirect to order details
redirect('order-details.php?id=' . $order_id);
?>