<?php
namespace App\Repositories;

class PurchaseRepository extends BaseRepository {
    
    public function create($data) {
        $sql = "INSERT INTO purchases (
                    transaction_id, reference_number, verification_token,
                    car_id, user_id, buyer_name, buyer_email, buyer_phone,
                    base_price, marketplace_fee, tax, total_amount,
                    status, escrow_status, payment_method, expires_at
                ) VALUES (
                    :transaction_id, :reference_number, :verification_token,
                    :car_id, :user_id, :buyer_name, :buyer_email, :buyer_phone,
                    :base_price, :marketplace_fee, :tax, :total_amount,
                    :status, :escrow_status, :payment_method, :expires_at
                )";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($data);
        return $this->db->lastInsertId();
    }

    public function findByTransactionId($transactionId) {
        $stmt = $this->db->prepare("SELECT * FROM purchases WHERE transaction_id = :id");
        $stmt->execute(['id' => $transactionId]);
        return $stmt->fetch();
    }

    public function updateStatus($id, $status, $escrowStatus = null) {
        $sql = "UPDATE purchases SET status = :status";
        $params = ['id' => $id, 'status' => $status];
        
        if ($escrowStatus) {
            $sql .= ", escrow_status = :escrow_status";
            $params['escrow_status'] = $escrowStatus;
        }
        
        $sql .= " WHERE id = :id";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute($params);
    }

    public function generateUniqueReference() {
        $ref = 'REF-' . strtoupper(substr(md5(uniqid()), 0, 8));
        // Check if exists
        $stmt = $this->db->prepare("SELECT id FROM purchases WHERE reference_number = :ref");
        $stmt->execute(['ref' => $ref]);
        if ($stmt->fetch()) {
            return $this->generateUniqueReference();
        }
        return $ref;
    }
}