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

  // 2. Fetch Existing Data (GET) - This runs first to populate $row for use in POST
  if(isset($_GET['id'])) {
      $id = $_GET['id'];
      $branch = $_SESSION['branch'];
      
      // Secure Fetch
      $stmt = $conn->prepare("SELECT a.*, e.e_name, e.e_id as emp_code, s.name as site_name 
                              FROM attendance a 
                              LEFT JOIN emp_details e ON a.emp_id = e.e_id AND e.branch = a.branch
                              LEFT JOIN site s ON a.site = s.id
                              WHERE a.id = :id AND a.branch = :branch LIMIT 1");
      $stmt->execute([':id' => $id, ':branch' => $branch]);
      $row = $stmt->fetch(PDO::FETCH_ASSOC);

      if(!$row) {
          echo "<script>alert('Record not found or access denied.'); window.location.href='current-attendance.php';</script>";
          exit;
      }
  }

  // 3. Handle Update (POST)
  if(isset($_POST["submit"]))
  {
    $id = $_GET['id']; // Keep ID from URL
    $sitename = $_POST['sitename'];
    $attendance = $_POST['attendance'];
    $advance_deduction = !empty($_POST['advance_deduction']) ? $_POST['advance_deduction'] : 0;
    $spc_allow = !empty($_POST['spc_allow']) ? $_POST['spc_allow'] : 0;
    
    // Checkbox Handling
    $block = isset($_POST['b']) ? "yes" : "";
    $check = isset($_POST['c']) ? "yes" : "";
    $only_ot = isset($_POST['only_ot']) ? "yes" : "";

    // VALIDATION 1: Mutual Exclusivity
    if($block == 'yes' && $check == 'yes') { 
        $message = "<div class='alert alert-danger border-0 bg-danger alert-dismissible fade show'>
                        <div class='text-white'>Error: Both Hold Salary and Cheque Payment cannot be selected at the same time.</div>
                        <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                    </div>";
    }
    else {
        // ------------------------------------------------------------------
        // VALIDATION 2: FULL DUPLICATE CHECK (The Fix)
        // Check if an entry with these EXACT details exists for this employee 
        // in this month/year, excluding the current record ($id).
        // ------------------------------------------------------------------
        $dup_sql = "SELECT id FROM attendance
                    WHERE emp_id = :emp_id
                      AND month = :month
                      AND year = :year
                      AND branch = :branch
                      AND site = :site
                      AND attendance = :attendance
                      AND only_ot = :only_ot
                      AND block = :block
                      AND `check` = :check
                      AND advance_deduction = :adv
                      AND id != :id  /* Crucial: Don't count self */
                    LIMIT 1";

        $dup_stmt = $conn->prepare($dup_sql);
        $dup_stmt->execute([
            ':emp_id' => $row['emp_id'],    // From fetched existing data
            ':month'  => $row['month'],     // From fetched existing data
            ':year'   => $row['year'],      // From fetched existing data
            ':branch' => $_SESSION['branch'],
            ':site'   => $sitename,
            ':attendance' => $attendance,
            ':only_ot' => $only_ot,
            ':block' => $block,
            ':check' => $check,
            ':adv' => $advance_deduction,
            ':id' => $id
        ]);

        if ($dup_stmt->rowCount() > 0) {
            // DUPLICATE FOUND - BLOCK UPDATE
            $message = "<div class='alert alert-warning border-0 bg-warning alert-dismissible fade show'>
                            <div class='text-dark'>
                                <strong>Update Blocked:</strong> An identical attendance record already exists for this employee in this month. 
                                <br>Updating this would create a duplicate.
                            </div>
                            <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                        </div>";
        } 
        else {
            // NO DUPLICATE - PROCEED WITH UPDATE
            $query = "UPDATE `attendance` SET 
                        `site` = :site,
                        `attendance` = :attendance,
                        `only_ot` = :only_ot,
                        `block` = :block,
                        `check` = :check,
                        `advance_deduction` = :adv,
                        `spc_allow` = :spc 
                      WHERE `id` = :id AND `branch` = :branch";
            
            $stmt = $conn->prepare($query);
            $result = $stmt->execute([
                ':site' => $sitename,
                ':attendance' => $attendance,
                ':only_ot' => $only_ot,
                ':block' => $block,
                ':check' => $check,
                ':adv' => $advance_deduction,
                ':spc' => $spc_allow,
                ':id' => $id,
                ':branch' => $_SESSION['branch']
            ]);

            if($result) { 
                 $message = "<script>alert('Attendance updated successfully.'); window.location.href = 'current-attendance.php';</script>";
            } else {
                 $message = "<div class='alert alert-danger border-0 bg-danger alert-dismissible fade show'>
                                <div class='text-white'>Technical Error. Contact the Developer.</div>
                             </div>";
            }
        }
    }
} 
?>

<!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/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="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">

    <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" />
    <script src="assets/js/jquery.min.js"></script>

    <title>Edit Attendance</title>

    <style>
        .card {
            border: none;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .form-label {
            color: #1e293b !important;
            font-weight: 700;
            font-size: 1rem;
            margin-bottom: 0.5rem;
            display: block; 
        }

        .text-danger-star {
            color: #dc3545;
            font-weight: bold;
            margin-left: 3px;
        }

        .form-control, .form-select {
            border: 1px solid #cbd5e1;
            padding: 0.7rem 1rem; 
            font-size: 1rem;
            border-radius: 6px;
        }
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        /* BIGGER TOGGLES */
        .form-switch .form-check-input {
            width: 3.5em; 
            height: 1.75em; 
            margin-top: 0.1em;
            cursor: pointer;
        }
        .form-switch .form-check-label {
            padding-left: 10px;
            font-size: 1.1rem;
            padding-top: 2px;
            color: #334155;
            font-weight: 500;
        }
        
        /* Read Only Input Style */
        .form-control[readonly] {
            background-color: #f1f5f9;
            opacity: 1;
        }
    </style>
  </head>
  <body>
    
  <div class="wrapper">
    <?php include'system/header.php'?>

    <div class="page-content-wrapper">
      <div class="page-content">

        <div class="row">
             <div class="col-xl-10 mx-auto">
                 <?php echo $message; ?>
             </div>
        </div>

        <div class="row">
          <div class="col-xl-10 mx-auto">
             
             <div class="card border-top border-0 border-4 border-primary">
               <div class="card-body p-4">

                <div class="d-flex align-items-center justify-content-between mb-4">
                    <div>
                        <h5 class="mb-0 text-primary">Edit Attendance</h5>
                        <p class="mb-0 text-secondary">Updating Record ID: <strong><?php echo $_GET['id']; ?></strong></p>
                    </div>
                </div>
                <hr class="mb-4" />

                <form method="POST" enctype="multipart/form-data" class="row g-4">
                    
                    <div class="col-md-6">
                        <label class="form-label">Employee Name (Read Only)</label>
                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($row['e_name'] . " (" . $row['emp_code'] . ")"); ?>" readonly>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">Site Name <span class="text-danger-star">*</span></label>
                        <select class="form-select" name="sitename" required>
                            <?php
                            $stmt = $conn->prepare("SELECT * FROM site WHERE branch = ? ORDER BY name ASC");
                            $stmt->execute([$_SESSION['branch']]);
                            $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            foreach($sites as $site) {
                                $selected = ($site['id'] == $row['site']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $site['id']; ?>" <?php echo $selected; ?>><?php echo $site['name']; ?></option>
                            <?php } ?>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Attendance Days <span class="text-danger-star">*</span></label>
                        <input type="number" step="0.5" class="form-control" name="attendance" value="<?php echo $row['attendance']; ?>" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Advance Deduction</label>
                        <input type="number" class="form-control" name="advance_deduction" value="<?php echo $row['advance_deduction']; ?>">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Special Allowance</label>
                        <input type="number" class="form-control" name="spc_allow" value="<?php echo $row['spc_allow']; ?>">
                    </div>

                    <div class="col-md-12">
                      <div class="p-4 border rounded bg-light">
                          <h6 class="mb-4 text-secondary">Payment Options & Flags</h6>
                          <div class="d-flex flex-wrap gap-5">
                            
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="b" value="yes" id="checkBlock" <?php if($row['block'] == 'yes') echo 'checked'; ?>>
                                <label class="form-check-label" for="checkBlock">Hold Salary</label>
                            </div>

                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="c" value="yes" id="checkCheque" <?php if($row['check'] == 'yes') echo 'checked'; ?>>
                                <label class="form-check-label" for="checkCheque">Cheque Payment</label>
                            </div>

                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="only_ot" value="yes" id="checkOT" <?php if($row['only_ot'] == 'yes') echo 'checked'; ?>>
                                <label class="form-check-label" for="checkOT">Only OT</label>
                            </div>
                          </div>
                      </div>
                    </div>

                    <div class="col-12">
                     <div class="alert alert-warning border-0 bg-warning bg-opacity-10 py-2">
                        <div class="d-flex align-items-center">
                            <div class="fs-3 text-warning me-2"><i class="bi bi-exclamation-triangle-fill"></i></div>
                            <div class="small text-dark">
                                "Hold Salary" and "Cheque Payment" are mutually exclusive. Selecting one will unselect the other.
                            </div>
                        </div>
                    </div>
                  </div>

                    <div class="col-12 text-end">
                        <a href="current-attendance.php" class="btn btn-secondary px-4 me-2">Cancel</a>
                        <button type="submit" name="submit" class="btn btn-primary px-4">Update Attendance</button>
                    </div>

                </form>

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

      </div>
    </div>
    
    <script>
    $(document).ready(function() {
        // Mutual Exclusivity Logic for Switches
        $('#checkBlock').change(function() {
            if($(this).is(':checked')) {
                $('#checkCheque').prop('checked', false);
            }
        });

        $('#checkCheque').change(function() {
            if($(this).is(':checked')) {
                $('#checkBlock').prop('checked', false);
            }
        });
    });
    </script>

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