<?php
  session_start();
  // 1. Security Check
  if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php");
    die();
  }
  require_once 'system/conn.php';

  // =======================================================
  //  HELPER FUNCTION: CHECK USAGE
  // =======================================================
  function isSiteInUse($conn, $site_id, $branch_id) {
      $stmt1 = $conn->prepare("SELECT id FROM attendance WHERE site = ? AND branch = ? LIMIT 1");
      $stmt1->execute([$site_id, $branch_id]);
      if($stmt1->rowCount() > 0) return true;

      try {
          $stmt2 = $conn->prepare("SELECT site FROM prv_attendance WHERE site = ? AND branch = ? LIMIT 1");
          $stmt2->execute([$site_id, $branch_id]);
          if($stmt2->rowCount() > 0) return true;
      } catch (Exception $e) { }

      return false;
  }

  // =======================================================
  //  ACTION 1: ADD NEW SITE
  // =======================================================
  if(isset($_POST['add_site_btn'])) {
      $site_name = trim($_POST['site_name']);
      $branch_id = $_SESSION['branch'];
      $updated_date = date("Y-m-d"); 

      if(!empty($site_name)) {
          $check = $conn->prepare("SELECT id FROM site WHERE name = ? AND branch = ?");
          $check->execute([$site_name, $branch_id]);
          
          if($check->rowCount() > 0) {
              echo "<script>alert('Error: Site Name already exists!');</script>";
          } else {
              $sql = "INSERT INTO site (name, branch, updated_date) VALUES (?, ?, ?)";
              $stmt = $conn->prepare($sql);
              if($stmt->execute([$site_name, $branch_id, $updated_date])) {
                  echo "<script>alert('Site Added Successfully!'); window.location.href='site-list.php';</script>"; 
              } else {
                  echo "<script>alert('Database Error.');</script>";
              }
          }
      }
  }

  // =======================================================
  //  ACTION 2: EDIT SITE
  // =======================================================
  if(isset($_POST['update_site_btn'])) {
      $edit_id = $_POST['edit_id'];
      $edit_name = trim($_POST['edit_name']);
      $updated_date = date("Y-m-d");
      $branch_id = $_SESSION['branch'];

      if(isSiteInUse($conn, $edit_id, $branch_id)) {
           echo "<script>alert('Security Alert: Cannot Edit. This site is currently in use.'); window.location.href='site-list.php';</script>";
      } else {
          if(!empty($edit_name) && !empty($edit_id)) {
              $update = $conn->prepare("UPDATE site SET name = ?, updated_date = ? WHERE id = ?");
              if($update->execute([$edit_name, $updated_date, $edit_id])) {
                  echo "<script>alert('Site Updated Successfully!'); window.location.href='site-list.php';</script>";
              } else {
                  echo "<script>alert('Error Updating Site');</script>";
              }
          }
      }
  }

  // =======================================================
  //  ACTION 3: DELETE SITE
  // =======================================================
  if(isset($_POST['delete_site_id'])) {
      $del_id = $_POST['delete_site_id'];
      $branch_id = $_SESSION['branch'];

      if(isSiteInUse($conn, $del_id, $branch_id)) {
          echo "<script>alert('Security Alert: Cannot Delete. This site is in use.'); window.location.href='site-list.php';</script>";
      } else {
          $del = $conn->prepare("DELETE FROM site WHERE id = ?");
          if($del->execute([$del_id])) {
              echo "<script>alert('Site Deleted Successfully'); window.location.href='site-list.php';</script>";
          } else {
              echo "<script>alert('Error Deleting Site');</script>";
          }
      }
  }
?>
<!doctype html>
<html lang="en" class="semi-dark">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <link href="assets/css/pace.min.css" rel="stylesheet" />
    <script src="assets/js/pace.min.js"></script>
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <link href="assets/plugins/datatable/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    
    <link href="assets/css/dark-theme.css" rel="stylesheet" />
    <link href="assets/css/semi-dark.css" rel="stylesheet" />
    <link href="assets/css/header-colors.css" rel="stylesheet" />
    
    <title>Site List</title>
    <style>
        /* Replicate original icon link styling */
        .invoice-action-edit, .invoice-action-view {
            font-size: 1.2rem;
            padding: 0 5px;
            cursor: pointer;
        }
        .invoice-action-edit { color: #0d6efd; } /* Primary Blue */
        .invoice-action-view { color: #dc3545; } /* Danger Red */
        
        /* Styling for disabled state */
        .action-disabled {
            color: #6c757d !important; /* Muted Grey */
            cursor: not-allowed;
            opacity: 0.7;
        }
        /* Button that looks like a link for delete form */
        .btn-link-submit {
            background: none;
            border: none;
            padding: 0;
            margin: 0 5px;
        }
    </style>
  </head>
  <body>
    
    <div class="wrapper">
    <?php include'system/header.php'?>
      
        <div class="page-content-wrapper">
          <div class="page-content">

          <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
            <div class="breadcrumb-title pe-3">View All Sites</div>
            <div class="ms-auto">
                <button type="button" class="btn btn-success px-5" data-bs-toggle="modal" data-bs-target="#addSiteModal">
                    <i class="bi bi-plus-lg me-2"></i>Add New Site
                </button>
            </div>
          </div>

            <hr/>
            
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="example2" class="table table-striped table-bordered">
                            <thead>
                                <tr>
                                    <th>SR No</th>
                                    <th>Site ID</th>
                                    <th>Site Name</th>
                                    <th>Last Updated</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php   
                                  $cnt = 1;
                                  $stmt = $conn->prepare("SELECT * FROM site WHERE branch = ? ORDER BY id DESC");
                                  $stmt->execute([$_SESSION['branch']]);
                                  $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                  
                                  foreach($sites as $row) {   
                                      $in_use = isSiteInUse($conn, $row['id'], $_SESSION['branch']);
                                      $alert_msg = "Cannot Edit/Delete: This site is linked to existing attendance records.";
                                ?>
                                <tr>
                                    <td><?php echo $cnt;?></td>
                                    <td><?php echo $row['id'];?></td>
                                    <td><strong><?php echo $row['name'];?></strong></td>
                                    <td><?php echo $row['updated_date'];?></td>
                                    <td>
                                        <div class="invoice-action d-flex justify-content-center">
                                            
                                            <?php if($in_use): ?>
                                                <a href="javascript:;" class="invoice-action-edit action-disabled" onclick="alert('<?php echo $alert_msg; ?>')" title="Disabled: Site is in use">
                                                    <i class="bi bi-lock-fill"></i>
                                                </a>
                                            <?php else: ?>
                                                <a href="javascript:;" class="invoice-action-edit edit-btn" 
                                                   data-bs-toggle="modal" 
                                                   data-bs-target="#editSiteModal"
                                                   data-id="<?php echo $row['id']; ?>" 
                                                   data-name="<?php echo $row['name']; ?>"
                                                   title="Edit Site">
                                                    <i class="bi bi-pencil-square"></i>
                                                </a>
                                            <?php endif; ?>

                                            <?php if($in_use): ?>
                                                <a href="javascript:;" class="invoice-action-view action-disabled ms-2" onclick="alert('<?php echo $alert_msg; ?>')" title="Disabled: Site is in use">
                                                    <i class="bi bi-lock-fill"></i>
                                                </a>
                                            <?php else: ?>
                                                <form method="POST" onsubmit="return confirm('Are you sure you want to delete this site?');" style="display:inline;">
                                                    <input type="hidden" name="delete_site_id" value="<?php echo $row['id']; ?>">
                                                    <button type="submit" class="btn-link-submit invoice-action-view ms-2" title="Delete Site">
                                                        <i class="bi bi-trash-fill"></i>
                                                    </button>
                                                </form>
                                            <?php endif; ?>

                                        </div>
                                    </td>
                                </tr>
                                <?php $cnt++; } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

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

    <div class="modal fade" id="addSiteModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header border-bottom-0">
            <h5 class="modal-title text-success">Add New Site</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <form method="POST">
              <div class="modal-body">
                  <div class="mb-3">
                    <label class="form-label fw-bold">Site Name</label>
                    <input type="text" class="form-control" name="site_name" required autocomplete="off">
                  </div>
              </div>
              <div class="modal-footer border-top-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" name="add_site_btn" class="btn btn-success px-4">Save</button>
              </div>
          </form>
        </div>
      </div>
    </div>

    <div class="modal fade" id="editSiteModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header border-bottom-0">
            <h5 class="modal-title text-primary">Edit Site</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <form method="POST">
              <div class="modal-body">
                  <input type="hidden" name="edit_id" id="edit_site_id">
                  <div class="mb-3">
                    <label class="form-label fw-bold">Site Name</label>
                    <input type="text" class="form-control" name="edit_name" id="edit_site_name" required autocomplete="off">
                  </div>
              </div>
              <div class="modal-footer border-top-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" name="update_site_btn" class="btn btn-primary px-4">Update</button>
              </div>
          </form>
        </div>
      </div>
    </div>

    <?php include'system/footer.php'?>

    <script>
        $(document).ready(function() {
            // Pass data to Edit Modal on click
            $('.edit-btn').on('click', function() {
                var id = $(this).data('id');
                var name = $(this).data('name');
                $('#edit_site_id').val(id);
                $('#edit_site_name').val(name);
            });
        });
    </script>