<?php 
require_once('header.php'); 
// require_once('config.php'); // Database connection


// CSV Upload and Processing
if(isset($_POST['upload_csv'])) {
    if($_FILES['csv_file']['name']) {
        $filename = $_FILES['csv_file']['tmp_name'];
        $file = fopen($filename, "r");

        $success_entries = [];
        $failed_entries = [];

        // Skip header row
        fgetcsv($file);

        while(($data = fgetcsv($file, 1000, ",")) !== FALSE) {
            $client_id = 1;
            $cust_code = trim($data[0]);
            $cust_name = trim($data[1]);
            $cust_phone = trim($data[2]);
            $cust_address = trim($data[3]);
            $cust_city = trim($data[4]);
            $cust_state = trim($data[5]);
            $cust_zip = trim($data[6]);
            $destination_city = trim($data[7]);

            // Validation
            if(empty($cust_code) || empty($cust_name) || empty($cust_address) || empty($cust_zip) || empty($cust_city) || empty($cust_state)) {
                $failed_entries[] = [$cust_code, "Missing required fields"];
                continue;
            }

            // Check if consignee code already exists
            $stmt = $pdo->prepare("SELECT * FROM tbl_customer WHERE cust_code = ?");
            $stmt->execute([$cust_code]);
            if($stmt->rowCount() > 0) {
                $failed_entries[] = [$cust_code, "Already exists"];
                continue;
            }

            // Insert new consignee
            $insert_stmt = $pdo->prepare("INSERT INTO tbl_customer (client_id, cust_code, cust_name, cust_phone, cust_address, cust_city, cust_state, cust_zip, destination_city) VALUES (?,?,?,?,?,?,?,?,?)");
            $insert_stmt->execute([$client_id, $cust_code, $cust_name, $cust_phone, $cust_address, $cust_city, $cust_state, $cust_zip, $destination_city]);

            $success_entries[] = [$cust_code, "Success"];
        }
        fclose($file);

        // Generate status CSV
        $status_filename = "upload_status.csv";
        $status_file = fopen($status_filename, "w");
        fputcsv($status_file, ["Customer Code", "Status"]);
        foreach ($success_entries as $entry) fputcsv($status_file, $entry);
        foreach ($failed_entries as $entry) fputcsv($status_file, $entry);
        fclose($status_file);

        $success_message = "CSV processed. <a href='$status_filename' download>Download Status Report</a>";
    } else {
        $error_message = "Please upload a CSV file.";
    }
}
?>

<section class="content">
    <div class="row">
        <div class="col-md-4">
            <h4><i class="fa fa-upload"></i> Bulk Upload Consignees</h4>
        </div>
        <div class="col-md-8" style="text-align: right;">
            <a href="customer.php" class="btn btn-warning btn-sm"><i class="fa fa-arrow-left"></i> Back to Consignee List</a>
        </div>
    </div> 

    <div class="row">
        <div class="col-md-12">
            <?php if(isset($error_message) && $error_message != ''): ?>
                <div class="callout callout-danger">
                    <p><?php echo $error_message; ?></p>
                </div>
            <?php endif; ?>

            <?php if(isset($success_message) && $success_message != ''): ?>
                <div class="callout callout-success">
                    <p><?php echo $success_message; ?></p>
                </div>
            <?php endif; ?>

            <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
                <div class="box box-info">
                    <div class="box-body">
                        <div class="form-group">
                            <label for="" class="col-sm-2 control-label">Upload CSV File <span>*</span></label>
                            <div class="col-sm-6">
                                <input type="file" name="csv_file" class="form-control" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-sm-2 control-label"></label>
                            <div class="col-sm-6">
                                <button type="submit" class="btn btn-success pull-left" name="upload_csv">Upload</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>

            <h4>CSV Format:</h4>
            <p>Ensure your CSV file follows this column order:</p>
            <pre>Customer Code, Customer Name, Customer Phone, Customer Address, Customer City, Customer State, Customer Zip, Destination City</pre>

            <br>
            <a href="download_sample_consignee_csv.php" class="btn btn-primary">Download Sample CSV</a>
        </div>
    </div>
</section>

<?php require_once('footer.php'); ?>
