<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) { session_start(); }
include 'db_config.php'; 

$message = "";

// ফর্ম সাবমিট হলে ডাটা প্রসেসিং
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_purchase'])) {
    // এরর এড়ানোর জন্য ?? '' (Null Coalescing) ব্যবহার করা হয়েছে
    $seller_name = mysqli_real_escape_string($conn, $_POST['seller_name'] ?? '');
    $seller_phone = mysqli_real_escape_string($conn, $_POST['seller_phone'] ?? '');
    $seller_nid = mysqli_real_escape_string($conn, $_POST['seller_nid'] ?? '');
    $ref_phone = mysqli_real_escape_string($conn, $_POST['ref_phone'] ?? ''); // এরর ফিক্স
    $ref_nid = mysqli_real_escape_string($conn, $_POST['ref_nid'] ?? '');     // এরর ফিক্স
    $model = mysqli_real_escape_string($conn, $_POST['model'] ?? '');
    $imei1 = mysqli_real_escape_string($conn, $_POST['imei1'] ?? '');
    $imei2 = mysqli_real_escape_string($conn, $_POST['imei2'] ?? '');
    $storage = mysqli_real_escape_string($conn, $_POST['storage'] ?? '');
    $battery = mysqli_real_escape_string($conn, $_POST['battery'] ?? '');
    $color = mysqli_real_escape_string($conn, $_POST['color'] ?? '');
    $buying_price = mysqli_real_escape_string($conn, $_POST['buying_price'] ?? '0');
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method'] ?? '');

    // চেকলিস্ট প্রসেসিং
    $checks = [];
    $opt = ['disp'=>'Display','cam'=>'Camera','sec'=>'Security','net'=>'Network','box'=>'Box','chr'=>'Charger','war'=>'Warranty','rep'=>'No Repair'];
    foreach($opt as $k => $v) { if(isset($_POST[$k])) $checks[] = $v; }
    $check_list = implode(", ", $checks);

    // বিক্রেতার ছবি
    $photo_path = "";
    if (!empty($_FILES['seller_photo']['name'])) {
        $target_dir = "uploads/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
        $file_name = "seller_" . time() . ".jpg";
        $target_file = $target_dir . $file_name;
        move_uploaded_file($_FILES["seller_photo"]["tmp_name"], $target_file);
        $photo_path = $target_file;
    }

    // স্বাক্ষর প্রসেসিং
    $signature_data = "";
    if (!empty($_FILES['signature_file']['name'])) {
        $sig_file = "uploads/sig_" . time() . ".png";
        move_uploaded_file($_FILES["signature_file"]["tmp_name"], $sig_file);
        $signature_data = $sig_file;
    } else {
        $signature_data = $_POST['signature_data'] ?? '';
    }

    $sql = "INSERT INTO mobile_purchases (seller_name, seller_phone, seller_nid, ref_phone, ref_nid, seller_photo, signature, model, imei1, imei2, storage, battery, color, check_list, buying_price, payment_method) 
            VALUES ('$seller_name', '$seller_phone', '$seller_nid', '$ref_phone', '$ref_nid', '$photo_path', '$signature_data', '$model', '$imei1', '$imei2', '$storage', '$battery', '$color', '$check_list', '$buying_price', '$payment_method')";

    if (mysqli_query($conn, $sql)) {
        $last_id = mysqli_insert_id($conn);
        $message = "<div class='alert success'>✅ সফলভাবে সেভ হয়েছে! <a href='view_mobile_details.php?id=$last_id' style='color:#065f46; font-weight:bold;'>মেমো দেখুন</a></div>";
    } else {
        $message = "<div class='alert danger'>❌ এরর: " . mysqli_error($conn) . "</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Mobile Buy Form - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --primary: #1e3a8a; --bg: #f3f4f6; }
        body { font-family: 'Segoe UI', sans-serif; background: var(--bg); margin: 0; display: flex; overflow-x: hidden; }
        
        /* Sidebar Fix for Mobile */
        .sidebar-wrapper { width: 250px; flex-shrink: 0; position: fixed; height: 100vh; background: #2c3e50; z-index: 1000; transition: 0.3s; left: 0; }
        .main-content { flex-grow: 1; margin-left: 250px; width: calc(100% - 250px); min-height: 100vh; padding: 20px; transition: 0.3s; position: relative; z-index: 1; }

        /* Mobile Menu Toggle */
        .menu-toggle { display: none; background: var(--primary); color: white; border: none; padding: 12px 18px; border-radius: 8px; cursor: pointer; position: fixed; top: 15px; left: 15px; z-index: 2000; box-shadow: 0 4px 10px rgba(0,0,0,0.2); }

        .form-card { max-width: 950px; margin: auto; background: #fff; padding: 30px; border-radius: 15px; box-shadow: 0 5px 25px rgba(0,0,0,0.1); }
        .section-header { background: #eef2ff; color: var(--primary); padding: 12px 15px; border-left: 5px solid var(--primary); font-weight: bold; margin: 25px 0 15px; border-radius: 4px; font-size: 16px; }
        
        .grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; }
        .input-group { margin-bottom: 12px; }
        label { display: block; font-size: 13px; font-weight: 600; margin-bottom: 6px; color: #374151; }
        input, select { width: 100%; padding: 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 14px; box-sizing: border-box; background: #fff; -webkit-appearance: none; }

        .media-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .media-box { border: 2px dashed #d1d5db; padding: 20px; border-radius: 12px; text-align: center; background: #fcfcfc; }
        
        /* Canvas Fix for Mobile Touch */
        canvas { background: #fff; border: 1px solid #999; width: 100%; height: 180px; border-radius: 8px; cursor: crosshair; touch-action: none; margin-top: 10px; }

        .check-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
        .check-item { display: flex; align-items: center; gap: 10px; font-size: 14px; background: #f9fafb; padding: 12px; border-radius: 8px; border: 1px solid #e5e7eb; cursor: pointer; }
        .check-item input { width: 20px; height: 20px; cursor: pointer; }

        .submit-btn { background: var(--primary); color: #fff; border: none; padding: 18px; width: 100%; border-radius: 12px; font-size: 18px; font-weight: bold; cursor: pointer; margin-top: 30px; transition: 0.3s; box-shadow: 0 4px 12px rgba(30, 58, 138, 0.2); }

        .alert { padding: 15px; border-radius: 10px; margin-bottom: 25px; text-align: center; font-weight: bold; font-size: 14px; }
        .success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .danger { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

        /* Mobile Specific Fixes */
        @media (max-width: 768px) {
            .menu-toggle { display: block; }
            .sidebar-wrapper { left: -250px; }
            .sidebar-wrapper.active { left: 0; box-shadow: 5px 0 15px rgba(0,0,0,0.3); }
            .main-content { margin-left: 0; width: 100%; padding: 15px; padding-top: 75px; }
            .grid { grid-template-columns: 1fr; }
            .media-grid { grid-template-columns: 1fr; }
            .check-grid { grid-template-columns: 1fr 1fr; }
            .form-card { padding: 20px; }
        }
    </style>
</head>
<body>

    <!-- মোবাইলের মেনু বাটন -->
    <button class="menu-toggle" id="btnToggle"><i class="fas fa-bars"></i> মেনু</button>

    <div class="sidebar-wrapper" id="mySidebar">
        <?php include 'sidebar.php'; ?>
    </div>

    <div class="main-content" id="mainContent">
        <div class="form-card">
            <h2 style="text-align:center; color:var(--primary); margin-bottom:25px;"><i class="fas fa-mobile-alt"></i> মোবাইল ক্রয় ফরম</h2>
            
            <?php echo $message; ?>

            <form id="purchaseForm" method="POST" enctype="multipart/form-data">
                
                <div class="section-header">১. বিক্রেতার তথ্য</div>
                <div class="grid">
                    <div class="input-group"><label>বিক্রেতার নাম</label><input type="text" name="seller_name" placeholder="নাম লিখুন" required></div>
                    <div class="input-group"><label>মোবাইল নম্বর</label><input type="tel" name="seller_phone" placeholder="০১৯..." required></div>
                    <div class="input-group"><label>NID নম্বর</label><input type="text" name="seller_nid" placeholder="NID নম্বর"></div>
                </div>

                <!-- Missing Fields added here to fix PHP Warning -->
                <div class="grid">
                    <div class="input-group"><label>রেফারেন্স মোবাইল</label><input type="tel" name="ref_phone" placeholder="পরিবারের মোবাইল"></div>
                    <div class="input-group"><label>রেফারেন্স NID</label><input type="text" name="ref_nid" placeholder="রেফারেন্স NID"></div>
                </div>

                <div class="media-grid">
                    <div class="media-box">
                        <label>📷 বিক্রেতার ছবি</label>
                        <input type="file" name="seller_photo" accept="image/*" capture="user" style="margin-top:10px">
                    </div>
                    <div class="media-box">
                        <label>✍️ বিক্রেতার স্বাক্ষর</label>
                        <input type="file" name="signature_file" accept="image/*" style="margin-bottom:10px;">
                        <canvas id="sig-canvas"></canvas>
                        <input type="hidden" name="signature_data" id="signature_data">
                        <button type="button" id="btnClear" style="margin-top:10px; padding:8px 15px; cursor:pointer; border-radius:5px; border:1px solid #ccc;">Clear Drawing</button>
                    </div>
                </div>

                <div class="section-header">২. ফোনের বিবরণ</div>
                <div class="grid">
                    <div class="input-group"><label>ব্র্যান্ড / মডেল</label><input type="text" name="model" required></div>
                    <div class="input-group"><label>IMEI ১</label><input type="text" name="imei1" required></div>
                    <div class="input-group"><label>Ram/Rom</label><input type="text" name="storage" placeholder="যেমন: 8/128"></div>
                </div>

                <div class="section-header">৩. চেকলিস্ট ও মূল্য</div>
                <div class="check-grid">
                    <label class="check-item"><input type="checkbox" name="disp"> ডিসপ্লে ওকে</label>
                    <label class="check-item"><input type="checkbox" name="box"> বক্স আছে</label>
                    <label class="check-item"><input type="checkbox" name="war"> ওয়ারেন্টি আছে</label>
                    <label class="check-item"><input type="checkbox" name="cam"> ক্যামেরা ওকে</label>
                </div>

                <div class="grid" style="margin-top:20px;">
                    <div class="input-group"><label>ক্রয়মূল্য (৳)</label><input type="number" name="buying_price" required></div>
                    <div class="input-group">
                        <label>পেমেন্ট মাধ্যম</label>
                        <select name="payment_method">
                            <option value="Cash">Cash</option>
                            <option value="Bkash">Bkash</option>
                            <option value="Nagad">Nagad</option>
                        </select>
                    </div>
                </div>

                <button type="submit" name="save_purchase" class="submit-btn">Save Information</button>
            </form>
        </div>
    </div>

    <script>
        // Sidebar Toggle Script
        const btnToggle = document.getElementById('btnToggle');
        const sidebar = document.getElementById('mySidebar');
        btnToggle.addEventListener('click', () => {
            sidebar.classList.toggle('active');
        });

        // ক্যানভাসে ড্রয়িং লজিক (Touch and Mouse Support)
        const canvas = document.getElementById('sig-canvas');
        const ctx = canvas.getContext('2d');
        let drawing = false;

        function initCanvas() {
            canvas.width = canvas.offsetWidth;
            canvas.height = canvas.offsetHeight;
            ctx.lineWidth = 2;
            ctx.lineCap = 'round';
            ctx.strokeStyle = '#000';
        }
        window.addEventListener('load', initCanvas);
        window.addEventListener('resize', initCanvas);

        const getPos = e => {
            const r = canvas.getBoundingClientRect();
            const clientX = e.clientX || (e.touches && e.touches[0].clientX);
            const clientY = e.clientY || (e.touches && e.touches[0].clientY);
            return { x: clientX - r.left, y: clientY - r.top };
        };

        const start = e => { 
            drawing = true; 
            const p = getPos(e); 
            ctx.beginPath(); 
            ctx.moveTo(p.x, p.y); 
            if(e.touches) e.preventDefault(); 
        };
        const draw = e => { 
            if(!drawing) return; 
            const p = getPos(e); 
            ctx.lineTo(p.x, p.y); 
            ctx.stroke(); 
            if(e.touches) e.preventDefault(); 
        };
        const stop = () => { drawing = false; };

        canvas.addEventListener('mousedown', start);
        canvas.addEventListener('mousemove', draw);
        window.addEventListener('mouseup', stop);
        canvas.addEventListener('touchstart', start, {passive: false});
        canvas.addEventListener('touchmove', draw, {passive: false});
        window.addEventListener('touchend', stop);

        document.getElementById('btnClear').addEventListener('click', () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        });

        document.getElementById('purchaseForm').onsubmit = function() {
            const blank = document.createElement('canvas');
            blank.width = canvas.width;
            blank.height = canvas.height;
            if (canvas.toDataURL() !== blank.toDataURL()) {
                document.getElementById('signature_data').value = canvas.toDataURL();
            }
        };
    </script>
</body>
</html>
<?php ob_end_flush(); ?>