<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Provera da li je korisnik prijavljen kao admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Provera ID-ja porudžbine
$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($order_id <= 0) {
    header('Location: /admin/orders/');
    exit;
}

// Dohvatanje podataka o porudžbini
$order = get_row("SELECT * FROM orders WHERE id = ?", [$order_id]);
if (!$order) {
    die("Porudžbina nije pronađena.");
}

// Dohvatanje stavki porudžbine
$order_items = get_rows("
    SELECT oi.*, p.name as product_name, p.sku 
    FROM order_items oi
    LEFT JOIN products p ON oi.product_id = p.id
    WHERE oi.order_id = ?
    ORDER BY oi.id ASC
", [$order_id]);

// Dohvatanje podataka o kompaniji
$company = [
    'name' => 'AGRAS D.O.O.',
    'address' => 'Oskara Daviča 2',
    'city' => 'Kragujevac',
    'zip' => '34000',
    'phone' => '065/8-065-065',
    'email' => 'info@hugong-aparati.rs',
    'website' => 'www.hugong-aparati.rs',
    'pib' => '113904929',
    'mb' => '21942626',
    'bank_account' => '160-6000001790434-25',
    'bank_name' => 'Banca Intesa'
];

// Generisanje broja računa
$invoice_number = 'F-' . date('Ymd') . '-' . $order['id'];

// Datum izdavanja računa
$invoice_date = date('d.m.Y.');

// Rok plaćanja (2 dana od danas)
$due_date = date('d.m.Y.', strtotime('+2 days'));

// Porez (PDV stopa)
$tax_rate = 20; // 20%

// Izračunavanje osnovice i PDV-a
$subtotal = $order['total'] / (1 + $tax_rate / 100); // Osnovica bez PDV-a
$tax_amount = $order['total'] - $subtotal; // Iznos PDV-a
?>
<!DOCTYPE html>
<html lang="sr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Predračun #<?php echo $invoice_number; ?></title>
    <style>
        body {
            font-family: Arial, sans-serif;
            font-size: 12pt;
            line-height: 1.5;
            margin: 0;
            padding: 0;
            color: #333;
        }
        .invoice-container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ddd;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .invoice-header {
            margin-bottom: 30px;
        }
        .invoice-title {
            font-size: 24pt;
            font-weight: bold;
            color: #0077cc;
            margin: 0 0 10px 0;
            text-align: center;
            border-bottom: 2px solid #0077cc;
            padding-bottom: 10px;
        }
        .company-info {
            float: left;
            width: 60%;
        }
        .invoice-info {
            float: right;
            width: 35%;
            text-align: right;
        }
        .clearfix::after {
            content: "";
            clear: both;
            display: table;
        }
        .company-name {
            font-size: 16pt;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .invoice-details {
            margin-bottom: 5px;
            font-weight: bold;
        }
        .customer-info, .payment-info {
            margin-bottom: 20px;
        }
        .section-title {
            font-weight: bold;
            margin-bottom: 5px;
            font-size: 14pt;
            color: #0077cc;
            border-bottom: 1px solid #ddd;
            padding-bottom: 5px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f8f8;
            font-weight: bold;
        }
        .text-right {
            text-align: right;
        }
        .totals {
            width: 350px;
            float: right;
            margin-bottom: 20px;
        }
        .totals table {
            width: 100%;
        }
        .totals th {
            text-align: right;
        }
        .total-row {
            font-weight: bold;
            font-size: 14pt;
        }
        .footer {
            border-top: 1px solid #ddd;
            padding-top: 10px;
            margin-top: 50px;
            font-size: 10pt;
            color: #666;
            text-align: center;
        }
        .signature {
            margin-top: 60px;
            margin-bottom: 20px;
        }
        .signature-line {
            border-top: 1px solid #333;
            width: 200px;
            margin-top: 50px;
            margin-bottom: 10px;
            display: inline-block;
        }
        @media print {
            .no-print {
                display: none;
            }
            .invoice-container {
                border: none;
                margin: 0;
                padding: 0;
                box-shadow: none;
            }
            body {
                font-size: 10pt;
            }
            .invoice-title {
                font-size: 20pt;
            }
        }
    </style>
</head>
<body>
    <div class="invoice-container">
        <!-- Dugme za štampanje (ne prikazuje se pri štampanju) -->
        <div class="no-print" style="text-align: right; margin-bottom: 20px;">
            <button onclick="window.print();" style="padding: 8px 16px; background-color: #0077cc; color: white; border: none; cursor: pointer; border-radius: 4px;">Štampaj predračun</button>
            <button onclick="window.close();" style="padding: 8px 16px; background-color: #f44336; color: white; border: none; cursor: pointer; margin-left: 10px; border-radius: 4px;">Zatvori</button>
        </div>
        
        <!-- Zaglavlje računa -->
        <div class="invoice-header">
            <div class="invoice-title">PREDRAČUN</div>
            
            <div class="clearfix">
                <div class="company-info">
                    <div class="company-name"><?php echo $company['name']; ?></div>
                    <p>
                        <?php echo $company['address']; ?><br>
                        <?php echo $company['zip']; ?> <?php echo $company['city']; ?><br>
                        PIB: <?php echo $company['pib']; ?><br>
                        Matični broj: <?php echo $company['mb']; ?><br>
                        Tel: <?php echo $company['phone']; ?><br>
                        Email: <?php echo $company['email']; ?><br>
                        Web: <?php echo $company['website']; ?>
                    </p>
                </div>
                
                <div class="invoice-info">
                    <p class="invoice-details">Predračun broj: <?php echo $invoice_number; ?></p>
                    <p class="invoice-details">Datum izdavanja: <?php echo $invoice_date; ?></p>
                    <p class="invoice-details">Rok plaćanja: <?php echo $due_date; ?></p>
                    <p class="invoice-details">Broj porudžbine: <?php echo $order['order_number']; ?></p>
                </div>
            </div>
        </div>
        
        <div class="clearfix">
            <!-- Podaci o kupcu -->
            <div class="customer-info" style="float: left; width: 48%;">
                <div class="section-title">Podaci o kupcu</div>
                <p>
                    <strong>Ime i prezime:</strong> <?php echo htmlspecialchars($order['name']); ?><br>
                    <?php if (!empty($order['email'])): ?>
                    <strong>Email:</strong> <?php echo $order['email']; ?><br>
                    <?php endif; ?>
                    <?php if (!empty($order['phone'])): ?>
                    <strong>Telefon:</strong> <?php echo $order['phone']; ?><br>
                    <?php endif; ?>
                    <strong>Adresa:</strong> <?php echo htmlspecialchars($order['address']); ?><br>
                    <strong>Mesto:</strong> <?php echo $order['zip']; ?> <?php echo htmlspecialchars($order['city']); ?>
                </p>
            </div>
            
            <!-- Podaci o plaćanju -->
            <div class="payment-info" style="float: right; width: 48%;">
                <div class="section-title">Podaci o plaćanju</div>
                <p>
                    <strong>Način plaćanja:</strong> <?php echo get_payment_method_name($order['payment_method']); ?><br>
                    <strong>Način dostave:</strong> <?php echo get_shipping_method_name($order['shipping_method']); ?><br>
                    <strong>Banka:</strong> <?php echo $company['bank_name']; ?><br>
                    <strong>Tekući račun:</strong> <?php echo $company['bank_account']; ?><br>
                    <strong>Poziv na broj:</strong> <?php echo $invoice_number; ?>
                </p>
            </div>
        </div>
        
        <div class="clearfix"></div>
        
        <!-- Tabela stavki -->
        <div class="section-title">Stavke predračuna</div>
        <table>
            <thead>
                <tr>
                    <th style="width: 40px;">RB</th>
                    <th>Proizvod</th>
                    <th>Šifra</th>
                    <th class="text-right">Jedinična cena</th>
                    <th class="text-right" style="width: 60px;">Kol.</th>
                    <th class="text-right">Ukupno bez PDV</th>
                    <th class="text-right">PDV</th>
                    <th class="text-right">Ukupno sa PDV</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($order_items)): ?>
                    <tr>
                        <td colspan="8" style="text-align: center;">Nema stavki na predračunu</td>
                    </tr>
                <?php else: ?>
                    <?php $total_without_tax = 0; ?>
                    <?php $total_tax = 0; ?>
                    <?php foreach ($order_items as $index => $item): ?>
                        <?php 
                        // Izračunavanje cene bez PDV-a
                        $price_without_tax = $item['price'] / (1 + $tax_rate / 100);
                        $item_tax = $item['price'] - $price_without_tax;
                        
                        // Ukupno za stavku
                        $item_total_without_tax = $price_without_tax * $item['quantity'];
                        $item_total_tax = $item_tax * $item['quantity'];
                        $item_total = $item['price'] * $item['quantity'];
                        
                        // Dodavanje na ukupno
                        $total_without_tax += $item_total_without_tax;
                        $total_tax += $item_total_tax;
                        ?>
                        <tr>
                            <td><?php echo $index + 1; ?></td>
                            <td><?php echo htmlspecialchars($item['product_name']); ?></td>
                            <td><?php echo $item['sku']; ?></td>
                            <td class="text-right"><?php echo number_format($price_without_tax, 2, ',', '.') . ' RSD'; ?></td>
                            <td class="text-right"><?php echo $item['quantity']; ?></td>
                            <td class="text-right"><?php echo number_format($item_total_without_tax, 2, ',', '.') . ' RSD'; ?></td>
                            <td class="text-right"><?php echo number_format($item_total_tax, 2, ',', '.') . ' RSD'; ?></td>
                            <td class="text-right"><?php echo number_format($item_total, 2, ',', '.') . ' RSD'; ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
        
        <!-- Ukupno -->
        <div class="totals">
            <table>
                <tr>
                    <th>Ukupno bez PDV:</th>
                    <td class="text-right"><?php echo number_format($subtotal, 2, ',', '.') . ' RSD'; ?></td>
                </tr>
                <tr>
                    <th>PDV (<?php echo $tax_rate; ?>%):</th>
                    <td class="text-right"><?php echo number_format($tax_amount, 2, ',', '.') . ' RSD'; ?></td>
                </tr>
                <tr class="total-row">
                    <th>UKUPNO ZA UPLATU:</th>
                    <td class="text-right"><?php echo format_price($order['total']); ?></td>
                </tr>
            </table>
        </div>
        
        <div class="clearfix"></div>
        
        <!-- Napomena -->
        <?php if (!empty($order['notes'])): ?>
        <div class="notes" style="margin-top: 20px;">
            <div class="section-title">Napomena</div>
            <p><?php echo nl2br(htmlspecialchars($order['notes'])); ?></p>
        </div>
        <?php endif; ?>
        
        <!-- Potpis -->
        <div class="signature" style="text-align: right;">
            <div class="signature-line"></div>
            <div>Potpis i pečat</div>
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <p>
                <?php echo $company['name']; ?> | <?php echo $company['address']; ?>, <?php echo $company['zip']; ?> <?php echo $company['city']; ?><br>
                PIB: <?php echo $company['pib']; ?> | Matični broj: <?php echo $company['mb']; ?> | Tekući račun: <?php echo $company['bank_account']; ?><br>
                Tel: <?php echo $company['phone']; ?> | Email: <?php echo $company['email']; ?> | Web: <?php echo $company['website']; ?>
            </p>
        </div>
    </div>
</body>
</html>