<?php
session_start();

// 1. SECURITY: Ensure User is Logged In
if(empty($_SESSION['branch']) || $_SESSION['branch'] == ''){
    header("Location: index.php");
    die();
}

require_once 'system/conn.php';

// =============================================================
//  2. GLOBAL DATE LOGIC & COUNT
// =============================================================
$date = explode('-', date("Y-m-d", strtotime("last day of previous month")));
$month = $date[1];
$year = $date[0];
$branch = $_SESSION['branch'];

// Count existing attendance
$cnt_sql = "SELECT COUNT(*) FROM attendance WHERE month = ? AND year = ? AND branch = ?";
$cnt_stmt = $conn->prepare($cnt_sql);
$cnt_stmt->execute([$month, $year, $branch]);
$attendance_count = $cnt_stmt->fetchColumn();

// =============================================================
//  3. AJAX HANDLER 1: Fetch Advance Amount
// =============================================================
if(isset($_POST['action']) && $_POST['action'] == 'fetch_advance' && isset($_POST['empp_id'])) {
    
    $empp_id = $_POST['empp_id'];
    $ajax_branch = $_SESSION['branch']; 

    $sql = "SELECT remaining_amount FROM advance WHERE e_id = ? AND branch = ? LIMIT 1";
    $sth = $conn->prepare($sql);
    $sth->execute([$empp_id, $ajax_branch]);
    
    $row = $sth->fetch(PDO::FETCH_ASSOC);
    
    // Output ONLY the number
    echo ($row && isset($row['remaining_amount'])) ? $row['remaining_amount'] : '0';
    exit; 
}

// =============================================================
//  4. AJAX HANDLER 2: Check History (NEW ADDITION)
// =============================================================
// =============================================================
//  4. AJAX HANDLER 2: Check History (Full Details)
// =============================================================
if(isset($_POST['action']) && $_POST['action'] == 'check_history' && isset($_POST['empp_id'])) {
    
    $empp_id = $_POST['empp_id'];
    $ajax_branch = $_SESSION['branch'];
    
    // Fetch FULL records + Site Name
    $sql = "SELECT a.*, s.name as site_name 
            FROM attendance a 
            LEFT JOIN site s ON a.site = s.id 
            WHERE a.emp_id = ? AND a.month = ? AND a.year = ? AND a.branch = ?";
            
    $sth = $conn->prepare($sql);
    $sth->execute([$empp_id, $month, $year, $ajax_branch]);
    $records = $sth->fetchAll(PDO::FETCH_ASSOC);
    $count = count($records);

    if($count > 0) {
        // 1. Display Header with Number of Records Found
        echo "<div class='mt-2 text-danger fw-bold small border-bottom border-danger pb-1 mb-1'>
                <i class='bi bi-exclamation-triangle-fill me-1'></i> Found $count Existing Record(s):
              </div>";

        // 2. Loop through each record and display in a separate row
        foreach($records as $row) {
            $s_name = $row['site_name'] ? $row['site_name'] : 'Unknown Site';
            
            // Build the data string
            $info_parts = [];
            $info_parts[] = "<strong>$s_name</strong>";
            $info_parts[] = "Days: <strong>{$row['attendance']}</strong>";
            
            // Only show money fields if they have value
            if($row['advance_deduction'] > 0) $info_parts[] = "Adv: {$row['advance_deduction']}";
            if($row['spc_allow'] > 0) $info_parts[] = "Spc: {$row['spc_allow']}";
            
            // Add Flags (Colored Text)
            if($row['block'] == 'yes') $info_parts[] = "<span class='text-danger fw-bold'>HOLD</span>";
            if($row['check'] == 'yes') $info_parts[] = "<span class='text-primary fw-bold'>CHQ</span>";
            if($row['only_ot'] == 'yes') $info_parts[] = "<span class='text-success fw-bold'>OT</span>";

            // Output the single row
            echo "<div class='text-dark small p-1 mb-1 bg-light border rounded' style='border-left: 3px solid #dc3545 !important;'>
                    " . implode(" <span class='text-muted'>|</span> ", $info_parts) . "
                  </div>";
        }
    }
    exit;
}

// =============================================================
//  5. FORM SUBMISSION LOGIC (YOUR ORIGINAL LOGIC)
// =============================================================
$message = "";

if(isset($_POST["submit_action"])) 
{
    $emp_id = $_POST['ename'];
    $site = $_POST['sitename'];
    $attendance = $_POST['attendance'];
    
    $spc_allow = !empty($_POST['spc_allow']) ? $_POST['spc_allow'] : 0;
    $advance_deduction = !empty($_POST['manual_a']) ? $_POST['manual_a'] : 0;
    
    $block = isset($_POST['b']) ? "yes" : "";
    $check = isset($_POST['c']) ? "yes" : "";
    $only_ot = isset($_POST['only_ot']) ? "yes" : "";

    // VALIDATION 1: Conflict Check
    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: Duplicate Check (YOUR EXACT QUERY)
        $check_sql = "SELECT id FROM attendance
                      WHERE emp_id = ?
                        AND month = ?
                        AND year = ?
                        AND branch = ?
                        AND site = ?
                        AND attendance = ?
                        AND only_ot = ?
                        AND block = ?
                        AND `check` = ?
                        AND spc_allow = ?
                      LIMIT 1";

        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->execute([
            $emp_id,
            $month,
            $year,
            $branch,
            $site,
            $attendance,
            $only_ot,
            $block,
            $check,
            $spc_allow,
        ]);

        if($check_stmt->rowCount() > 0) {
            $message = "<div class='alert alert-warning border-0 bg-warning alert-dismissible fade show'>
                            <div class='text-dark'>Error: Attendance for this employee for " . $month . "-" . $year . " already exists!</div>
                            <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                        </div>";
        } 
        else {
            // INSERTION
            $sql = "INSERT INTO attendance 
                    (`emp_id`, `month`, `year`, `site`, `attendance`, `only_ot`, `block`, `check`, `branch`, `spc_allow`, `advance_deduction`) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $insert_stmt = $conn->prepare($sql);
            $result = $insert_stmt->execute([
                $emp_id, $month, $year, $site, $attendance, $only_ot, $block, $check, $branch, $spc_allow, $advance_deduction
            ]);

            if($result) {
                if($_POST['submit_action'] == 'save_exit') {
                    $message = "<script>alert('Saved Successfully!'); window.location.href='home.php';</script>";
                } else {
                    $message = "<script>alert('Saved Successfully! Ready for next.'); window.location.href='add-attendance.php';</script>";
                }
            } else {
                $message = "<div class='alert alert-danger border-0 bg-danger alert-dismissible fade show'>
                                <div class='text-white'>Database Error: Could not insert attendance.</div>
                                <button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
                            </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>Add 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;
        }

        /* Info Text for Advance */
        .advance-info {
            font-size: 0.9rem;
            margin-top: 5px;
            display: block;
        }
    </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">Add Attendance</h5>
                        <p class="mb-0 text-secondary">Period: <strong><?php echo date('F Y', strtotime("last day of previous month")); ?></strong></p>
                    </div>
                    <div class="text-end">
                        <div class="badge rounded-pill bg-primary fs-6 p-2 px-3">
                            <i class="bi bi-people-fill me-2"></i>Entered So Far: <?php echo $attendance_count; ?>
                        </div>
                    </div>
                </div>
                
                <hr class="mb-4" />
                
                <form class="row g-4 needs-validation" novalidate method="post">

                  <div class="col-md-6">
                    <label for="ename" class="form-label">Enter Employee ID/Name <span class="text-danger-star">*</span></label>
                    
                    <input list="brow" id="ename" class="form-control" name="ename" required autocomplete="off" placeholder="Type to search...">
                    <datalist id="brow">
                      <?php 
                      $stmt = $conn->prepare("SELECT * FROM emp_details WHERE branch = ? AND status = '1' ORDER BY e_name ASC");
                      $stmt->execute([$_SESSION['branch']]);
                      $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                      foreach($users as $row) { ?>
                        <option value="<?php echo $row['e_id']?>"><?php echo $row['e_name'];?></option>
                      <?php } ?>
                    </datalist> 
                    
                    <div id="history_feedback" class="mt-2"></div>
                  </div>

                  <div class="col-md-6">
                    <label for="sitename" class="form-label">Select Site Name <span class="text-danger-star">*</span></label>
                    <select class="form-select" id="sitename" name="sitename" required>
                      <option value="">--- Select Site Name ---</option>
                      <?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 $row) { ?>
                          <option value="<?php echo $row['id']?>"><?php echo $row['name'];?></option>
                      <?php } ?>
                    </select>
                  </div>
                  
                  <div class="col-md-4">
                    <label for="attendance" class="form-label">Total Days <span class="text-danger-star">*</span></label>
                    <input type="number" step="0.5" class="form-control" id="attendance" name="attendance" placeholder="e.g. 26.5" required>
                  </div>
                  
                  <div class="col-md-4">
                    <label for="a_amt" class="form-label">Advance Deduction</label>
                    <input type="number" class="form-control" name="manual_a" id="a_amt" value="" placeholder="0">
                    
                    <span class="advance-info text-secondary">
                        Available Balance: <span id="display_advance_amt" class="text-primary fw-bold">---</span>
                    </span>
                  </div>
                  
                  <div class="col-md-4">
                    <label for="spc_allow" class="form-label">Special Allowance</label>
                    <input type="number" class="form-control" id="spc_allow" name="spc_allow" value="0">
                  </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">
                                <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">
                                <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">
                                <label class="form-check-label" for="checkOT">Only OT</label>
                            </div>
                          </div>
                          
                      </div>
                      <div class="small text-dark">Both "Hold Salary" and "Cheque Payment" can not be selected at a time.</div>
                  </div>
                  
                  <div class="col-12">
                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                        
                        <button type="reset" class="btn btn-secondary px-4 py-2" onclick="$('#display_advance_amt').text('---'); $('#history_feedback').html('');">
                            <i class="bi bi-arrow-counterclockwise me-2"></i>Reset
                        </button>

                        <div class="d-flex gap-2">
                            <button class="btn btn-success px-4 py-2" type="submit" name="submit_action" value="save_exit">
                                <i class="bi bi-check-circle me-2"></i>Save & Exit
                            </button>
                            
                            <button class="btn btn-primary px-4 py-2" type="submit" name="submit_action" value="save_add">
                                <i class="bi bi-plus-circle me-2"></i>Save & Add Another
                            </button>
                        </div>

                    </div>
                  </div>

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

      </div>
    </div>

    <script>
    $(document).ready(function() {
        
        // 1. AJAX LOGIC
        $('#ename').on('change', function() {
            var empp_id = this.value;
            
            // Clear previous feedback
            $("#history_feedback").html("");
            $("#display_advance_amt").text("---");
            
            if(empp_id){
                $("#display_advance_amt").text("Fetching...");
                
                // Call 1: Fetch Advance
                $.ajax({
                    url: "add-attendance.php", 
                    type: "POST",
                    data: { 
                        empp_id: empp_id,
                        action: 'fetch_advance' 
                    },
                    success: function(result){
                        $("#display_advance_amt").text(result); 
                    },
                    error: function() {
                        $("#display_advance_amt").text("Error");
                    }
                });

                // Call 2: Check History (NEW)
                $.ajax({
                    url: "add-attendance.php", 
                    type: "POST",
                    data: { 
                        empp_id: empp_id,
                        action: 'check_history' 
                    },
                    success: function(result){
                        $("#history_feedback").html(result); 
                    }
                });

            }
        });

        // 2. 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'; ?>