<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

$success = '';
$error = '';
$importResults = [];

// Handle CSV upload
if ($_POST && isset($_FILES['csvFile'])) {
    $uploadedFile = $_FILES['csvFile'];
    
    if ($uploadedFile['error'] === UPLOAD_ERR_OK) {
        $filePath = $uploadedFile['tmp_name'];
        
        if (($handle = fopen($filePath, "r")) !== FALSE) {
            $header = fgetcsv($handle); // Skip header row
            $imported = 0;
            $errors = 0;
            
            while (($row = fgetcsv($handle)) !== FALSE) {
                if (count($row) >= 5) { // Minimum required columns
                    $customerName = mysqli_real_escape_string($con, trim($row[0]));
                    $mobile = mysqli_real_escape_string($con, trim($row[1]));
                    $area = mysqli_real_escape_string($con, trim($row[2]));
                    $address = mysqli_real_escape_string($con, trim($row[3]));
                    $customerType = mysqli_real_escape_string($con, trim($row[4]));
                    $gmapLocation = isset($row[5]) ? mysqli_real_escape_string($con, trim($row[5])) : '';
                    
                    // Validate customer type
                    if (!in_array($customerType, ['Retail', 'Shop'])) {
                        $customerType = 'Retail'; // Default to Retail
                    }
                    
                    // Validate mobile number
                    if (!preg_match('/^[0-9]{10}$/', $mobile)) {
                        $importResults[] = "Row " . ($imported + $errors + 2) . ": Invalid mobile number - $mobile";
                        $errors++;
                        continue;
                    }
                    
                    // Check if mobile already exists
                    $checkQuery = "SELECT ID FROM tblcustomers WHERE Mobile = '$mobile' AND IsActive = 1";
                    $checkResult = mysqli_query($con, $checkQuery);
                    
                    if (mysqli_num_rows($checkResult) > 0) {
                        $importResults[] = "Row " . ($imported + $errors + 2) . ": Mobile number already exists - $mobile";
                        $errors++;
                        continue;
                    }
                    
                    // Insert customer
                    $insertQuery = "INSERT INTO tblcustomers (CustomerName, Mobile, Area, Address, GmapLocation, CustomerType, CreatedBy) 
                                   VALUES ('$customerName', '$mobile', '$area', '$address', '$gmapLocation', '$customerType', '$userId')";
                    
                    if (mysqli_query($con, $insertQuery)) {
                        $imported++;
                    } else {
                        $importResults[] = "Row " . ($imported + $errors + 2) . ": Database error - " . mysqli_error($con);
                        $errors++;
                    }
                } else {
                    $importResults[] = "Row " . ($imported + $errors + 2) . ": Insufficient data columns";
                    $errors++;
                }
            }
            
            fclose($handle);
            
            if ($imported > 0) {
                $success = "Successfully imported $imported customers.";
                if ($errors > 0) {
                    $success .= " $errors rows had errors.";
                }
            } else {
                $error = "No customers were imported. $errors rows had errors.";
            }
        } else {
            $error = "Unable to read the uploaded file.";
        }
    } else {
        $error = "File upload error: " . $uploadedFile['error'];
    }
}

// Download sample CSV
if (isset($_GET['download_sample'])) {
    $filename = 'customer_import_sample.csv';
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    $output = fopen('php://output', 'w');
    
    // Write header
    fputcsv($output, ['Customer Name', 'Mobile', 'Area', 'Address', 'Customer Type', 'Google Maps Link (Optional)']);
    
    // Write sample data
    fputcsv($output, ['Ravi Kumar', '9876543210', 'T. Nagar', '123 Main Street, T. Nagar, Chennai - 600017', 'Retail', 'https://maps.google.com/?q=13.0418,80.2341']);
    fputcsv($output, ['Sri Lakshmi Stores', '9876543211', 'Mylapore', '456 Market Road, Mylapore, Chennai - 600004', 'Shop', 'https://maps.google.com/?q=13.0339,80.2619']);
    fputcsv($output, ['Priya Devi', '9876543212', 'Adyar', '789 Second Street, Adyar, Chennai - 600020', 'Retail', '']);
    
    fclose($output);
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Import Customers | Mariyappa Nadar Ricemill</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <style>
        .upload-area {
            border: 2px dashed #4e73df;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            background-color: #f8f9fc;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            background-color: #eaecf4;
            border-color: #2e59d9;
        }
        .upload-area.dragover {
            background-color: #d1ecf1;
            border-color: #17a2b8;
        }
        .file-info {
            margin-top: 10px;
            padding: 8px;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 5px;
            color: #155724;
            font-size: 0.9rem;
        }
        .step-card {
            border: none;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
        }
        .step-number {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: linear-gradient(45deg, #4e73df, #36b9cc);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 12px;
            font-size: 0.9rem;
        }
        .card-body { padding: 1rem; }
        .card-header { padding: 0.75rem 1rem; }
        .form-group { margin-bottom: 0.75rem; }
        .alert { padding: 0.5rem 1rem; margin-bottom: 0.75rem; }
        .table-sm td, .table-sm th { padding: 0.4rem; font-size: 0.85rem; }
        
        @media (max-width: 768px) {
            .upload-area { padding: 20px; }
            .step-number { width: 30px; height: 30px; margin-right: 8px; font-size: 0.8rem; }
            .card-body, .card-header { padding: 0.75rem; }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">
                            <i class="fas fa-file-import text-primary mr-2"></i>
                            Import Customers
                        </h1>
                        <div class="d-none d-lg-inline-block">
                            <a href="customer-management.php" class="btn btn-secondary mr-2">
                                <i class="fas fa-users mr-2"></i>Manage Customers
                            </a>
                            <a href="?download_sample=1" class="btn btn-success">
                                <i class="fas fa-download mr-2"></i>Download Sample
                            </a>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Import Instructions -->
                        <div class="col-lg-4">
                            <div class="card step-card mb-4">
                                <div class="card-header bg-primary text-white">
                                    <h6 class="m-0 font-weight-bold">
                                        <i class="fas fa-info-circle mr-2"></i>Import Instructions
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex align-items-start mb-2">
                                        <div class="step-number">1</div>
                                        <div>
                                            <strong>Download Sample File</strong>
                                            <p class="text-muted mb-0 small">Click the "Download Sample" button to get the correct CSV format.</p>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex align-items-start mb-2">
                                        <div class="step-number">2</div>
                                        <div>
                                            <strong>Prepare Your Data</strong>
                                            <p class="text-muted mb-0 small">Fill in your customer data using the same format as the sample file.</p>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex align-items-start mb-2">
                                        <div class="step-number">3</div>
                                        <div>
                                            <strong>Upload CSV File</strong>
                                            <p class="text-muted mb-0 small">Upload your prepared CSV file using the form on the right.</p>
                                        </div>
                                    </div>
                                    
                                    <div class="alert alert-info mt-2">
                                        <h6 class="mb-1"><i class="fas fa-lightbulb mr-1"></i> Important Notes:</h6>
                                        <ul class="mb-0 pl-3 small">
                                            <li>Mobile numbers must be exactly 10 digits</li>
                                            <li>Customer Type must be either "Retail" or "Shop"</li>
                                            <li>Duplicate mobile numbers will be skipped</li>
                                            <li>Google Maps link is optional</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- CSV Format -->
                            <div class="card step-card">
                                <div class="card-header bg-info text-white">
                                    <h6 class="m-0 font-weight-bold">
                                        <i class="fas fa-table mr-2"></i>Required CSV Format
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-sm table-bordered">
                                            <thead class="thead-light">
                                                <tr>
                                                    <th style="font-size: 0.8rem;">Column</th>
                                                    <th style="font-size: 0.8rem;">Required</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>Customer Name</td>
                                                    <td><span class="badge badge-danger">Yes</span></td>
                                                </tr>
                                                <tr>
                                                    <td>Mobile</td>
                                                    <td><span class="badge badge-danger">Yes</span></td>
                                                </tr>
                                                <tr>
                                                    <td>Area</td>
                                                    <td><span class="badge badge-danger">Yes</span></td>
                                                </tr>
                                                <tr>
                                                    <td>Address</td>
                                                    <td><span class="badge badge-danger">Yes</span></td>
                                                </tr>
                                                <tr>
                                                    <td>Customer Type</td>
                                                    <td><span class="badge badge-danger">Yes</span></td>
                                                </tr>
                                                <tr>
                                                    <td>Google Maps Link</td>
                                                    <td><span class="badge badge-secondary">No</span></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Upload Form -->
                        <div class="col-lg-8">
                            <div class="card step-card mb-4">
                                <div class="card-header bg-success text-white">
                                    <h6 class="m-0 font-weight-bold">
                                        <i class="fas fa-upload mr-2"></i>Upload Customer Data
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <form method="POST" enctype="multipart/form-data" id="uploadForm">
                                        <div class="upload-area" onclick="document.getElementById('csvFile').click()">
                                            <i class="fas fa-cloud-upload-alt fa-2x text-primary mb-2"></i>
                                            <h6 class="text-primary mb-1">Click to Upload CSV File</h6>
                                            <p class="text-muted mb-0 small">or drag and drop your file here</p>
                                            <input type="file" id="csvFile" name="csvFile" accept=".csv" style="display: none;" required>
                                        </div>
                                        
                                        <div id="fileInfo" class="file-info" style="display: none;">
                                            <i class="fas fa-file-csv mr-2"></i>
                                            <span id="fileName"></span>
                                            <span id="fileSize" class="text-muted ml-2"></span>
                                        </div>
                                        
                                        <div class="text-center mt-3">
                                            <button type="submit" class="btn btn-primary" id="uploadBtn" disabled>
                                                <i class="fas fa-upload mr-2"></i>Import Customers
                                            </button>
                                            <button type="button" class="btn btn-secondary ml-2" onclick="resetForm()">
                                                <i class="fas fa-times mr-2"></i>Reset
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <?php if (!empty($importResults)): ?>
                            <!-- Import Results -->
                            <div class="card step-card">
                                <div class="card-header bg-warning text-white">
                                    <h6 class="m-0 font-weight-bold">
                                        <i class="fas fa-exclamation-triangle mr-2"></i>Import Results
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-warning">
                                        <h6><i class="fas fa-info-circle mr-1"></i> The following issues were found:</h6>
                                    </div>
                                    <div style="max-height: 300px; overflow-y: auto;">
                                        <?php foreach ($importResults as $result): ?>
                                        <div class="alert alert-danger py-2 mb-1">
                                            <small><?php echo htmlspecialchars($result); ?></small>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
                <!-- /.container-fluid -->
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <?php include_once('includes/footer2.php');?>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>

    <script>
        const uploadArea = document.querySelector('.upload-area');
        const fileInput = document.getElementById('csvFile');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        const uploadBtn = document.getElementById('uploadBtn');

        // Drag and drop functionality
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                handleFileSelect();
            }
        });

        fileInput.addEventListener('change', handleFileSelect);

        function handleFileSelect() {
            const file = fileInput.files[0];
            if (file) {
                if (file.type === 'text/csv' || file.name.toLowerCase().endsWith('.csv')) {
                    fileName.textContent = file.name;
                    fileSize.textContent = `(${formatFileSize(file.size)})`;
                    fileInfo.style.display = 'block';
                    uploadBtn.disabled = false;
                } else {
                    alert('Please select a valid CSV file.');
                    resetForm();
                }
            }
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function resetForm() {
            fileInput.value = '';
            fileInfo.style.display = 'none';
            uploadBtn.disabled = true;
        }

        // Auto-dismiss alerts after 10 seconds
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 10000);
    </script>
</body>
</html>
