<?php
/**
 * Direct Test of Save Functionality
 * This will test saving statutory data directly
 */

require_once __DIR__ . '/includes/init.php';
requireLogin();

$db = getDB();
$siteId = getCurrentSiteId();
$userId = getCurrentUserId();

// Get first employee
$stmt = $db->prepare("SELECT employee_id, employee_code, first_name, last_name, pan_number, aadhar_number, remarks FROM employees WHERE site_id = ? LIMIT 1");
$stmt->execute([$siteId]);
$emp = $stmt->fetch(PDO::FETCH_ASSOC);

$message = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_save'])) {
    try {
        $employeeId = (int)$_POST['employee_id'];
        $panNumber = sanitize($_POST['pan_number'] ?? '');
        $aadharNumber = sanitize($_POST['aadhar_number'] ?? '');
        $remarks = sanitize($_POST['remarks'] ?? '');
        
        $sql = "UPDATE employees SET 
                pan_number = ?,
                aadhar_number = ?,
                remarks = ?,
                updated_by = ?,
                updated_at = CURRENT_TIMESTAMP
                WHERE employee_id = ? AND site_id = ?";
        
        $stmt = $db->prepare($sql);
        $result = $stmt->execute([
            $panNumber,
            $aadharNumber,
            $remarks,
            $userId,
            $employeeId,
            $siteId
        ]);
        
        $affectedRows = $stmt->rowCount();
        
        if ($result && $affectedRows > 0) {
            $message = "✅ SUCCESS! Data saved. Affected rows: {$affectedRows}";
            $success = true;
            
            // Refresh employee data
            $stmt = $db->prepare("SELECT employee_id, employee_code, first_name, last_name, pan_number, aadhar_number, remarks FROM employees WHERE employee_id = ?");
            $stmt->execute([$employeeId]);
            $emp = $stmt->fetch(PDO::FETCH_ASSOC);
        } else {
            $message = "⚠️ No rows affected. Employee ID: {$employeeId}, Site ID: {$siteId}";
        }
        
    } catch (Exception $e) {
        $message = "❌ ERROR: " . $e->getMessage();
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Direct Save Test</title>
    <style>
        body { font-family: Arial; padding: 20px; max-width: 800px; margin: 0 auto; }
        .form-group { margin: 15px 0; }
        label { display: inline-block; width: 150px; font-weight: bold; }
        input, textarea { padding: 8px; width: 400px; border: 1px solid #ddd; border-radius: 4px; }
        button { padding: 12px 24px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background: #218838; }
        .result { margin: 20px 0; padding: 15px; border-radius: 5px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        .current-values { background: #fff3cd; padding: 15px; border-radius: 5px; margin: 20px 0; }
    </style>
</head>
<body>
    <h2>Direct Save Test - Statutory Data</h2>
    
    <?php if ($message): ?>
        <div class="result <?php echo $success ? 'success' : 'error'; ?>">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <?php if ($emp): ?>
        <div class="info">
            <strong>Testing with Employee:</strong><br>
            ID: <?php echo $emp['employee_id']; ?><br>
            Code: <?php echo htmlspecialchars($emp['employee_code']); ?><br>
            Name: <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
        </div>
        
        <form method="POST">
            <input type="hidden" name="employee_id" value="<?php echo $emp['employee_id']; ?>">
            
            <div class="form-group">
                <label>PAN Number:</label>
                <input type="text" name="pan_number" 
                       value="<?php echo htmlspecialchars($emp['pan_number'] ?? ''); ?>" 
                       placeholder="Enter PAN Number (e.g., ABCDE1234F)"
                       maxlength="10">
            </div>
            
            <div class="form-group">
                <label>Aadhar Number:</label>
                <input type="text" name="aadhar_number" 
                       value="<?php echo htmlspecialchars($emp['aadhar_number'] ?? ''); ?>" 
                       placeholder="Enter Aadhar Number (12 digits)"
                       maxlength="12">
            </div>
            
            <div class="form-group">
                <label>Remarks:</label>
                <textarea name="remarks" rows="3" 
                          placeholder="Enter any remarks or notes"><?php echo htmlspecialchars($emp['remarks'] ?? ''); ?></textarea>
            </div>
            
            <button type="submit" name="test_save">💾 Save Data</button>
        </form>
        
        <div class="current-values">
            <h3>Current Values in Database:</h3>
            <p><strong>PAN Number:</strong> <?php echo htmlspecialchars($emp['pan_number'] ?? 'NULL'); ?></p>
            <p><strong>Aadhar Number:</strong> <?php echo htmlspecialchars($emp['aadhar_number'] ?? 'NULL'); ?></p>
            <p><strong>Remarks:</strong> <?php echo htmlspecialchars($emp['remarks'] ?? 'NULL'); ?></p>
        </div>
        
        <p><a href="modules/employee/new_joinee_statutory.php">← Back to New Joinee Statutory</a></p>
        
    <?php else: ?>
        <div class="error">
            <strong>No employees found!</strong><br>
            Please add an employee first: <a href="modules/employee/create.php">Add Employee</a>
        </div>
    <?php endif; ?>
    
    <hr>
    <h3>Debug Info:</h3>
    <div class="info">
        <p><strong>Site ID:</strong> <?php echo $siteId; ?></p>
        <p><strong>User ID:</strong> <?php echo $userId; ?></p>
        <p><strong>Database:</strong> <?php echo $db->query("SELECT DATABASE()")->fetchColumn(); ?></p>
    </div>
</body>
</html>

