<?php
/**
 * Dispute Model
 * File: app/Models/Dispute.php
 */

class Dispute {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    public function create($data) {
        $sql = "INSERT INTO disputes (
            order_id, raised_by, raised_by_type, dispute_type, 
            description, amount_involved, evidence_files, status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'open', NOW())";
        
        $result = $this->db->execute($sql, [
            $data['order_id'],
            $data['raised_by'],
            $data['raised_by_type'],
            $data['dispute_type'],
            $data['description'],
            $data['amount_involved'] ?? null,
            $data['evidence_files'] ?? null
        ]);
        
        return $result ? $this->db->lastInsertId() : false;
    }
    
    public function find($id) {
        $sql = "SELECT d.*, o.order_number, u.email as raised_by_email
                FROM disputes d
                JOIN orders o ON d.order_id = o.id
                JOIN users u ON d.raised_by = u.id
                WHERE d.id = ? LIMIT 1";
        return $this->db->fetch($sql, [$id]);
    }
    
    public function getAll($filters = [], $limit = 50) {
        $sql = "SELECT d.*, o.order_number, u.email
                FROM disputes d
                JOIN orders o ON d.order_id = o.id
                JOIN users u ON d.raised_by = u.id WHERE 1=1";
        $params = [];
        
        if (!empty($filters['status'])) {
            $sql .= " AND d.status = ?";
            $params[] = $filters['status'];
        }
        
        $sql .= " ORDER BY d.created_at DESC LIMIT ?";
        $params[] = $limit;
        
        return $this->db->fetchAll($sql, $params);
    }
    
    public function updateStatus($id, $status) {
        $sql = "UPDATE disputes SET status = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$status, $id]);
    }
    
    public function resolve($id, $admin_id, $resolution) {
        $sql = "UPDATE disputes SET status = 'resolved', resolution = ?, 
                resolved_by = ?, resolved_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, [$resolution, $admin_id, $id]);
    }
}
