<?php
ob_start();
include("connection.php");

// Add new company
if(isset($_POST['add_company'])) {

    $company_name = mysqli_real_escape_string($conn, $_POST['company_name']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $post = mysqli_real_escape_string($conn, $_POST['post']);
    $district = mysqli_real_escape_string($conn, $_POST['district']);
    $state = mysqli_real_escape_string($conn, $_POST['state']);
    $pin = mysqli_real_escape_string($conn, $_POST['pin']);
    $country = mysqli_real_escape_string($conn, $_POST['country']);
    $gst_number = mysqli_real_escape_string($conn, $_POST['gst_number']);
    $reg_date = mysqli_real_escape_string($conn, $_POST['reg_date']);
    $exp_date = mysqli_real_escape_string($conn, $_POST['exp_date']);
    
    // Handle file upload - check if file is uploaded
    $fileName = '';
    if(isset($_FILES["logo"]) && $_FILES["logo"]["error"] == 0 && !empty($_FILES["logo"]["name"])) {
        $targetDir = "company_logo/";
        $fileName = time() . "_" . basename($_FILES["logo"]["name"]);
        $targetFile = $targetDir . $fileName;
        $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
        $allowedTypes = ['jpg','jpeg','png','gif'];
        
        if(in_array($imageFileType,$allowedTypes)){
            if(!move_uploaded_file($_FILES["logo"]["tmp_name"], $targetFile)){
                $fileName = ''; // Reset if upload fails
            }
        } else {
            $fileName = ''; // Reset if file type not allowed
        }
    }
    
    $created_at = date('Y-m-d H:i:s');

    // Insert company
    $sql = mysqli_query($conn, "
        INSERT INTO `company`(`company_name`, `address`, `post`, `district`, `state`, `pin`, `country`, `gst_number`, `reg_date`, `exp_date`, `logo`, `created_at`)
        VALUES ('$company_name','$address','$post','$district','$state','$pin','$country','$gst_number','$reg_date','$exp_date','$fileName','$created_at')
    ");

    if($sql){
        echo "Company added successfully!";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}

// Fetch company data for edit
if(isset($_POST['fetch_company'])) {

    $company_id = $_POST['company_id'];

    $q = mysqli_query($conn,"
        SELECT * FROM company 
        WHERE id='$company_id'
        ORDER BY id ASC limit 1
    ");

    $data = mysqli_fetch_assoc($q);

    echo json_encode([
        "id"            => $data['id'],
        "company_name"  => $data['company_name'],
        "address"       => $data['address'],
        "post"          => $data['post'],
        "district"      => $data['district'],
        "state"         => $data['state'],
        "pin"           => $data['pin'],
        "country"       => $data['country'],
        "gst_number"    => $data['gst_number'],
        "reg_date"      => $data['reg_date'],
        "exp_date"      => $data['exp_date'],
        "logo"          => $data['logo']
    ]);
    exit;
}

// Edit company details
if(isset($_POST['edit_company'])) {

        $company_id = mysqli_real_escape_string($conn, $_POST['id']);
        $company_name = mysqli_real_escape_string($conn, $_POST['company_name']);
        $address = mysqli_real_escape_string($conn, $_POST['address']);
        $post = mysqli_real_escape_string($conn, $_POST['post']);
        $district = mysqli_real_escape_string($conn, $_POST['district']);
        $state = mysqli_real_escape_string($conn, $_POST['state']);
        $pin = mysqli_real_escape_string($conn, $_POST['pin']);
        $country = mysqli_real_escape_string($conn, $_POST['country']);
        $gst_number = mysqli_real_escape_string($conn, $_POST['gst_number']);
        $reg_date = mysqli_real_escape_string($conn, $_POST['reg_date']);
        $exp_date = mysqli_real_escape_string($conn, $_POST['exp_date']);
        $logo = mysqli_real_escape_string($conn, $_POST['logo']);
        
        // Handle file upload - check if file is uploaded
        $fileName = '';
        if(isset($_FILES["logo"]) && $_FILES["logo"]["error"] == 0 && !empty($_FILES["logo"]["name"])) {
            $targetDir = "company_logo/";
            $fileName = time() . "_" . basename($_FILES["logo"]["name"]);
            $targetFile = $targetDir . $fileName;
            $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
            $allowedTypes = ['jpg','jpeg','png','gif'];
            
            if(in_array($imageFileType,$allowedTypes)){
                if(!move_uploaded_file($_FILES["logo"]["tmp_name"], $targetFile)){
                    $fileName = ''; // Reset if upload fails
                }
            } else {
                $fileName = ''; // Reset if file type not allowed
            }
        }

        // Update company
        $sql = mysqli_query($conn, "
            UPDATE `company` SET 
            `company_name`='$company_name',
            `address`='$address',
            `post`='$post',
            `district`='$district',
            `state`='$state',
            `pin`='$pin',
            `country`='$country',
            `gst_number`='$gst_number',
            `reg_date`='$reg_date',
            `exp_date`='$exp_date'
            WHERE `id`='$company_id'
        ");
        
        if($fileName!='')
            {
                    $sql = mysqli_query($conn, "
                        UPDATE `company` SET `logo`='$fileName' WHERE `id`='$company_id'
                    ");
            }

        if ($sql) {
            if (mysqli_affected_rows($conn) > 0) {
                echo "Company updated successfully!";
            } else {
                echo "No changes made to company data.";
            }
        } else {
            echo "Error updating company: " . mysqli_error($conn);
        }
}

// Delete company
if(isset($_POST['delete_company'])) {

    $company_id = $_POST['company_id'];

    $q = mysqli_query($conn,"
        DELETE FROM `company` WHERE `id`='$company_id'
    ");

    if($q) {
        echo "Company deleted successfully!";
    } else {
        echo "Error deleting company: " . mysqli_error($conn);
    }
    exit;
}

?>
