<?php
// Ensure all required details are passed
if (
    !isset($_POST['customer_info'], $_POST['brand'], $_POST['model'], $_POST['gb'], $_POST['color'], $_POST['imei_or_sn'], $_POST['condition'], $_POST['buy_price'], $_POST['stock']) ||
    empty($_POST['customer_info']) || empty($_POST['brand']) || empty($_POST['model']) || empty($_POST['imei_or_sn']) || empty($_POST['condition']) || empty($_POST['buy_price']) || empty($_POST['stock'])
) {
    die('<h2>Error: Missing product or customer details. Please go back and try again.</h2>');
}

// Include database connection (config.php)
include('config.php');

// Fetch business details from business_locations table
$business_sql = "SELECT name, business_registration_number, mobile FROM business_locations LIMIT 1";
$business_result = $conn->query($business_sql);

// Check if data is available
if ($business_result && $business_result->num_rows > 0) {
    $business_row = $business_result->fetch_assoc();
    $business_name = $business_row['name'];
    $business_registration_number = $business_row['business_registration_number'];
    $business_mobile = $business_row['mobile'];
} else {
    $business_name = "Not Found";
    $business_registration_number = "Not Found";
}

// Retrieve product and customer details from POST
$customer_info = $_POST['customer_info'];
$product_brand = $_POST['brand'];
$gb = $_POST['gb'];
$color = $_POST['color'];
$product_model = $_POST['model'];
$imei_or_sn = $_POST['imei_or_sn'];
$product_condition = $_POST['condition'];
$buy_price = $_POST['buy_price'];
$stock = $_POST['stock'];

// Parse customer_info to extract Name, Mobile, and CPR
preg_match('/Name: (.*?), Mobile: (.*?), CPR: (.*)/', $customer_info, $matches);
if (count($matches) === 4) {
    $customer_name = $matches[1];
    $customer_number = $matches[2];
    $customer_cpr = $matches[3];
} else {
    die('<h2>Error: Unable to parse customer details. Ensure the format is correct.</h2>');
}

// Fetch the company settings (currency, time zone) from company_settings table
$settings_sql = "SELECT time_zone, currency FROM company_settings LIMIT 1";
$settings_result = $conn->query($settings_sql);

if ($settings_result && $settings_result->num_rows > 0) {
    $settings_row = $settings_result->fetch_assoc();
    $time_zone = $settings_row['time_zone'];
    $currency = $settings_row['currency'];
}

// Set the time zone according to the database value
date_default_timezone_set($time_zone);

// Get the current date and time
$current_date_time = date('d-m-Y H:i');

// Insert receipt details into gen_receipt table
$receipt_stmt = $conn->prepare("INSERT INTO gen_receipt (customer_info, brand, model, imei_or_sn, `condition`, color, gb, buy_price, stock) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

if ($receipt_stmt) {
    $receipt_stmt->bind_param("sssssssis", $customer_info, $product_brand, $product_model, $imei_or_sn, $product_condition, $color, $gb, $buy_price, $stock);
    $receipt_stmt->execute();
    $receipt_id = $conn->insert_id;
    $receipt_stmt->close();
} else {
    die('<h2>Error: Unable to save receipt. Please try again later.</h2>');
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Receipt</title>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .receipt-container {
            width: 210mm;
            /* A4 width */
            height: auto;
            /* Adjust height for content */
            padding: 20mm;
            background-color: #ffffff;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            box-sizing: border-box;
            text-align: center;
        }

        .receipt-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .receipt-header h1 {
            font-size: 24px;
            font-weight: 700;
            color: #007bff;
            margin: 0;
            text-transform: uppercase;
        }

        .receipt-header small {
            display: block;
            font-size: 14px;
            color: #6c757d;
        }

        .receipt-section {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px dashed #dee2e6;
        }

        .section-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #495057;
        }

        .section-content p {
            margin: 5px 0;
            font-size: 14px;
            color: #212529;
        }

        .divider {
            border: 0;
            border-top: 2px dashed #ced4da;
            margin: 20px 0;
        }

        .cpr-box {
            margin: 20px auto;
            text-align: center;
            width: 85.6mm;
            height: 53.98mm;
            border: 2px dashed #007bff;
            border-radius: 8px;
            font-size: 14px;
            font-weight: bold;
            color: #007bff;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f8f9fa;
            box-sizing: border-box;
        }

        .signatures {
            margin-top: 30px;
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            color: #6c757d;
        }

        .signatures div {
            text-align: center;
            width: 45%;
        }

        .signatures div hr {
            margin: 10px 0;
            border: none;
            border-top: 1px solid #ced4da;
        }

        .footer {
            text-align: center;
            font-size: 12px;
            color: #adb5bd;
            margin-top: 30px;
        }

        .action-buttons {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 20px;
        }

        .action-buttons a,
        .action-buttons button {
            display: inline-block;
            padding: 10px 20px;
            font-size: 16px;
            font-weight: bold;
            color: #fff;
            background-color: #007bff;
            border: none;
            border-radius: 5px;
            text-decoration: none;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .action-buttons a:hover,
        .action-buttons button:hover {
            background-color: #0056b3;
        }

        /* Print-specific styles */
        @media print {

            .action-buttons,
            .footer {
                display: none;
            }
        }
    </style>
</head>

<body onload="window.print();">

    <div class="receipt-container">
        <div class="receipt-header">
            <h1>Product Receipt</h1>
            <small>Date/Time: <?php echo htmlspecialchars($current_date_time); ?></small>
        </div>

        <div class="section-title">Business Information</div>
        <div class="section-content">
            <p><strong>Company:</strong> <?php echo htmlspecialchars($business_name); ?></p>
            <p><strong>CR:</strong> <?php echo htmlspecialchars($business_registration_number); ?></p>
            <p><strong>Mobile:</strong> <?php echo htmlspecialchars($business_mobile); ?></p>
            <small>Your Trusted Store</small>
        </div>

        <div class="receipt-section">
            <div class="section-title">Customer Details</div>
            <div class="section-content">
                <p><strong>Name:</strong> <?php echo htmlspecialchars($customer_name); ?></p>
                <p><strong>Mobile:</strong> <?php echo htmlspecialchars($customer_number); ?></p>
                <p><strong>CPR:</strong> <?php echo htmlspecialchars($customer_cpr); ?></p>
            </div>
        </div>

        <div class="receipt-section">
            <div class="section-title">Product Details</div>
            <div class="section-content">
                <p><strong>Brand:</strong> <?php echo htmlspecialchars($product_brand); ?></p>
                <p><strong>Model:</strong> <?php echo htmlspecialchars($product_model); ?></p>
                <p><strong>IMEI/SN:</strong> <?php echo htmlspecialchars($imei_or_sn); ?></p>
                <p><strong>Storage/Color:</strong> <?php echo htmlspecialchars($gb); ?>GB/<?php echo htmlspecialchars($color); ?></p>
                <p><strong>Condition:</strong> <?php echo htmlspecialchars($product_condition); ?></p>
                <p><strong>Buy Price:</strong> <?php echo htmlspecialchars($currency . number_format($buy_price, 2)); ?></p>
                <p><strong>Stock:</strong> <?php echo htmlspecialchars($stock); ?></p>
            </div>
        </div>

        <div class="cpr-box">CPR / ID BOX</div>

        <div class="divider"></div>

        <div class="signatures">
            <div>
                Customer Signature:
                <hr>
            </div>
            <div>
                Buyer Signature:
                <hr>
            </div>
        </div>

        <div class="action-buttons">
            <a href="view_receipt.php?id=<?php echo $receipt_id; ?>" target="_blank" class="view-button">View Receipt</a>
            <a href="admin_panel.php?page=view_products" class="back-button">Back to Products</a>
        </div>

        <div class="footer">
            &copy; 2025 Your Company. All Rights Reserved.
        </div>
    </div>

</body>

</html>