<?php
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: login.php');
    exit;
}
include('connection.php');
?>
<?php
$pageTitle = 'Company Registration';
$sidebarId = 'company-registration';
include 'adminheader.php';
?>

<div class="doctor-registration-page">
  <div>
    <div id="form-alerts"></div>

    <form class="doctor-form" onsubmit="return false;">
      <input type="hidden" id="hid_company_id">
      <input id="txt_company_name" placeholder="Company Name" required>
      <textarea id="txt_address" rows="2" placeholder="Address"></textarea>

      <div class="form-row">
        <input id="txt_post" placeholder="Post">
        <input id="txt_district" placeholder="District">
      </div>

      <div class="form-row">
        <input id="txt_state" placeholder="State">
        <input id="txt_pin" placeholder="Pin">
      </div>

      <input id="txt_country" placeholder="Country">
      <input id="txt_gst_number" placeholder="GST Number">

      <div class="form-row">
        <input type="date" id="txt_reg_date">
        <input type="date" id="txt_exp_date">
      </div>

      <div class="form-upload-group">
        <label class="upload-label">Upload Company Logo (JPG/PNG)</label>
        <input type="file" id="txt_logo" accept="image/*">
        <input type="hidden" id="txt_logo_old">
      </div>

      <div style="display:flex;gap:10px">
        <button type="submit" class="btn-add" id="btn_company_add" onclick="add_company();">Add</button>
        <button type="submit" class="btn-add" id="btn_company_update" style="display:none;" onclick="edit_company();">Update</button>
        <button type="button" class="btn-add" id="btn_company_cancel" style="background:#6b7280;display:none" onclick="cancelEdit()">Cancel</button>
      </div>
    </form>
  </div>

  <div class="doctor-right">
    <div class="doctor-toolbar">
      <div class="search-wrap">
        <input class="search-input" id="search-input" placeholder="Search…" oninput="renderTable()">
        <button class="search-go-btn">Go</button>
      </div>
    </div>

    <div class="doctor-table-wrap">
      <table class="doctor-table">
        <thead>
          <tr>
            <th>Company</th>
            <th>Logo</th>
            <th>GST</th>
            <th>District</th>
            <th>Action</th>
          </tr>
        </thead>

        <tbody id="table-body">
          <?php
            $query_company = "SELECT *
              FROM company 
              ORDER BY id ASC";

            $sql_company = mysqli_query($conn, $query_company);
            while($rss_company = mysqli_fetch_array($sql_company)){
          ?>
          <tr>
            <td><?php echo $rss_company['company_name']; ?></td>
            <td>
              <?php 
                if(!empty($rss_company['logo'])) {
                  echo '<img src="company_logo/' . $rss_company['logo'] . '" alt="Logo" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;">';
                } else {
                  echo '<span style="color: #999; font-size: 12px;">No Logo</span>';
                }
              ?>
            </td>
            <td><?php echo $rss_company['gst_number']; ?></td>
            <td><?php echo $rss_company['district']; ?></td>
            <td>
              <button onclick="fetch_company(<?php echo $rss_company['id']; ?>)">
                <i class="fa fa-edit"></i>
              </button>
              <button onclick="delete_company(<?php echo $rss_company['id']; ?>)">
                <i class="fa fa-trash"></i>
              </button>
            </td>
          </tr>
          <?php
            }
          ?>
        </tbody>

      </table>
    </div>
  </div>
</div>

<?php include 'adminfooter.php'; ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  // Required for sidebar
  sessionStorage.setItem('kottakal_admin', 'true');

   function add_company()
   {
      var formData = new FormData();
      formData.append("add_company", "1");
      formData.append("company_name", $('#txt_company_name').val());
      formData.append("address", $('#txt_address').val());
      formData.append("post", $('#txt_post').val());
      formData.append("district", $('#txt_district').val());
      formData.append("state", $('#txt_state').val());
      formData.append("pin", $('#txt_pin').val());
      formData.append("country", $('#txt_country').val());
      formData.append("gst_number", $('#txt_gst_number').val());
      formData.append("reg_date", $('#txt_reg_date').val());
      formData.append("exp_date", $('#txt_exp_date').val());
      
      // Append file if selected
      var logoFile = $('#txt_logo')[0].files[0];
      if(logoFile) {
          formData.append("logo", logoFile);
      }
      
      $.ajax({
         type: "POST",
         url: "company-registration_save.php",
         data: formData,
         contentType: false,
         processData: false,
         cache: true,
         success: function(response)
         {
          alert(response);
            setTimeout(function(){
               $('#txt_company_name').val('');
               $('#txt_address').val('');
               $('#txt_post').val('');
               $('#txt_district').val('');
               $('#txt_state').val('');
               $('#txt_pin').val('');
               $('#txt_country').val('');
               $('#txt_gst_number').val('');
               $('#txt_reg_date').val('');
               $('#txt_exp_date').val('');
               $('#txt_logo').val('');
               window.location.href='company-registration.php';                         	
               
               }, 3000);
         }
      }); 
   }

   function fetch_company(company_id) {
         $.ajax({
             type: "POST",
             url: "company-registration_save.php",
             dataType: "json",
             data: {
                 fetch_company: 1,
                 company_id: company_id
             },
             success: function(response) {
                 // Populate form fields with response
                 $('#hid_company_id').val(response.id);
                 $('#txt_company_name').val(response.company_name);
                 $('#txt_address').val(response.address);
                 $('#txt_post').val(response.post);
                 $('#txt_district').val(response.district);
                 $('#txt_state').val(response.state);
                 $('#txt_pin').val(response.pin);
                 $('#txt_country').val(response.country);
                 $('#txt_gst_number').val(response.gst_number);
                 $('#txt_reg_date').val(response.reg_date);
                 $('#txt_exp_date').val(response.exp_date);
                 $('#txt_logo_old').val(response.logo);

                 // Show/Hide buttons
                 $("#btn_company_add").hide();
                 $("#btn_company_update").show();
                 $("#btn_company_cancel").show();
             },
             error: function(xhr, status, error) {
                 console.error("AJAX Error:", status, error);
                 alert("Failed to fetch company data.");
             }
         });
     }

    function edit_company()
    {
          var formData = new FormData();
          formData.append("edit_company", "1");
          formData.append("id", $('#hid_company_id').val());
          formData.append("company_name", $('#txt_company_name').val());
          formData.append("address", $('#txt_address').val());
          formData.append("post", $('#txt_post').val());
          formData.append("district", $('#txt_district').val());
          formData.append("state", $('#txt_state').val());
          formData.append("pin", $('#txt_pin').val());
          formData.append("country", $('#txt_country').val());
          formData.append("gst_number", $('#txt_gst_number').val());
          formData.append("reg_date", $('#txt_reg_date').val());
          formData.append("exp_date", $('#txt_exp_date').val());
          
          // Append file if selected
          var logoFile = $('#txt_logo')[0].files[0];
          if(logoFile) {
              formData.append("logo", logoFile);
          }

          $.ajax({
             type: "POST",
             url: "company-registration_save.php",
             data: formData,
             contentType: false,
             processData: false,
             cache: true,
             success: function(response)
             {
                alert(response);
                setTimeout(function(){
                   window.location.reload();
                   }, 3000);
             }
          }); 
    }

    function delete_company(company_id)
    {
          if(confirm('Are you sure you want to delete this company?')) {
          $.ajax({
          type: "POST",
          url: "company-registration_save.php",
          data: {
             delete_company: 1,
             company_id: company_id                
          },
          success: function(response) {
             alert(response);
             window.location.reload();
          }
       });
       }
    }

    function cancelEdit() {
        $('#hid_company_id').val('');
        $('#txt_company_name').val('');
        $('#txt_address').val('');
        $('#txt_post').val('');
        $('#txt_district').val('');
        $('#txt_state').val('');
        $('#txt_pin').val('');
        $('#txt_country').val('');
        $('#txt_gst_number').val('');
        $('#txt_reg_date').val('');
        $('#txt_exp_date').val('');
        $('#txt_logo').val('');
        
        $("#btn_company_add").show();
        $("#btn_company_update").hide();
        $("#btn_company_cancel").hide();
    }

    function renderTable() {
        var searchValue = $('#search-input').val().toLowerCase();
        $('#table-body tr').filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(searchValue) > -1)
        });
    }
</script>