<?php
require_once 'Database.php';

class Delivery {
    private $db;

    public function __construct() {
        $this->db = new Database();
    }

    public function createDelivery($user_id, $data) {
        $stmt = $this->db->query(
            "INSERT INTO deliveries (user_id, pickup_location, delivery_location, package_description, package_weight, package_value, delivery_instructions, delivery_mode) 
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            [
                $user_id,
                $data['pickup_location'],
                $data['delivery_location'],
                $data['package_description'] ?? '',
                $data['package_weight'] ?? 1.0,
                $data['package_value'] ?? null,
                $data['delivery_instructions'] ?? null,
                $data['delivery_mode'] ?? 'standard'
            ]
        );

        return $this->db->lastInsertId();
    }

    public function getUserDeliveries($user_id, $limit = null) {
        $sql = "SELECT * FROM deliveries WHERE user_id = ? ORDER BY created_at DESC";
        $params = [$user_id];
        
        if ($limit) {
            $sql .= " LIMIT " . (int)$limit;
        }

        $stmt = $this->db->query($sql, $params);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getAvailableDeliveries() {
        $stmt = $this->db->query(
            "SELECT d.*, u.name as customer_name, u.phone as customer_phone
             FROM deliveries d 
             JOIN users u ON d.user_id = u.id 
             WHERE d.status = 'pending' 
             ORDER BY d.created_at DESC"
        );

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getRiderDeliveries($rider_id) {
        $stmt = $this->db->query(
            "SELECT d.*, u.name as customer_name, u.phone as customer_phone
             FROM deliveries d 
             JOIN users u ON d.user_id = u.id 
             WHERE d.rider_id = ? 
             ORDER BY d.created_at DESC",
            [$rider_id]
        );

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function acceptDelivery($delivery_id, $rider_id) {
        $stmt = $this->db->query(
            "UPDATE deliveries SET rider_id = ?, status = 'accepted', updated_at = NOW() 
             WHERE id = ? AND status = 'pending'",
            [$rider_id, $delivery_id]
        );

        return $stmt->rowCount() > 0;
    }

    public function updateStatus($delivery_id, $status, $rider_id = null) {
        $sql = "UPDATE deliveries SET status = ?, updated_at = NOW()";
        $params = [$status, $delivery_id];
        
        if ($rider_id) {
            $sql .= " WHERE id = ? AND rider_id = ?";
            $params[] = $rider_id;
        } else {
            $sql .= " WHERE id = ?";
        }

        $stmt = $this->db->query($sql, $params);
        return $stmt->rowCount() > 0;
    }

    public function getDeliveryStats() {
        $stats = [];
        
        // Total deliveries
        $stmt = $this->db->query("SELECT COUNT(*) as total FROM deliveries");
        $stats['total_deliveries'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];

        // Deliveries by status
        $stmt = $this->db->query("SELECT status, COUNT(*) as count FROM deliveries GROUP BY status");
        $stats['by_status'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Total revenue
        $stmt = $this->db->query("SELECT COALESCE(SUM(price), 0) as revenue FROM deliveries WHERE status = 'delivered'");
        $stats['total_revenue'] = $stmt->fetch(PDO::FETCH_ASSOC)['revenue'];

        return $stats;
    }

    public function getRiderStats($rider_id) {
        $stats = [];
        
        $stmt = $this->db->query(
            "SELECT status, COUNT(*) as count 
             FROM deliveries 
             WHERE rider_id = ? 
             GROUP BY status",
            [$rider_id]
        );
        
        $statusCounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $stats['pending'] = 0;
        $stats['active'] = 0;
        $stats['completed'] = 0;
        
        foreach ($statusCounts as $statusCount) {
            if (in_array($statusCount['status'], ['accepted', 'picked_up', 'in_transit'])) {
                $stats['active'] += $statusCount['count'];
            } elseif ($statusCount['status'] === 'delivered') {
                $stats['completed'] += $statusCount['count'];
            } elseif ($statusCount['status'] === 'pending') {
                $stats['pending'] += $statusCount['count'];
            }
        }

        return $stats;
    }

    public function getCompletedDeliveryCount($user_id) {
        $stmt = $this->db->query(
            "SELECT COUNT(*) FROM deliveries WHERE user_id = ? AND status = 'delivered'",
            [$user_id]
        );
        return (int)$stmt->fetchColumn();
    }
}
?>