<?php
require_once 'includes/config.php';
require_once 'includes/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = $_POST['product_id'];
    $competitor_url = $_POST['competitor_url'];
    $customer_email = $_POST['customer_email'];
    $comments = $_POST['comments'];

    // File upload handling
    $upload_dir = 'uploads/price_match_proofs/';
    $proof_file = $upload_dir . uniqid() . '_' . basename($_FILES['price_proof']['name']);
    
    if (move_uploaded_file($_FILES['price_proof']['tmp_name'], $proof_file)) {
        // Save to database
        $sql = "INSERT INTO price_match_requests 
                (product_id, competitor_url, customer_email, comments, proof_file, status) 
                VALUES (?, ?, ?, ?, ?, 'pending')";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $product_id, 
            $competitor_url, 
            $customer_email, 
            $comments, 
            $proof_file
        ]);

        // Send notification email to admin
        $admin_email = 'admin@hugong-aparati.rs';
        $subject = 'Nova Price Match zahtev';
        $message = "Nov zahtev za Price Match:\n
                    Proizvod ID: $product_id\n
                    Email: $customer_email\n
                    URL: $competitor_url";
        
        mail($admin_email, $subject, $message);

        echo json_response(['success' => true, 'message' => 'Zahtev uspešno poslat']);
    } else {
        echo json_response(['success' => false, 'message' => 'Greška u uploadovanju']);
    }
}