<?php
require_once __DIR__ . '/init.php';

// Suraksha jaanch: Sirf Admin aur Manager access kar sakte hain
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

// Chuni hui date aur user ko prapt karein
$selected_date = $_GET['target_date'] ?? date('Y-m-d');
$selected_user_id = isset($_GET['user_id']) && is_numeric($_GET['user_id']) ? (int)$_GET['user_id'] : null;

// --- FORM SUBMISSION LOGIC ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_target'])) {
    $user_id = (int)$_POST['user_id'];
    $new_target = (int)$_POST['new_target'];
    $target_date = $_POST['target_date'];
    $admin_id = $_SESSION['user_id'];

    if ($new_target >= 0) {
        // Temporary target ko save/update karein
        $sql = "INSERT INTO temporary_targets (user_id, target_date, target_value, set_by_user_id) 
                VALUES (?, ?, ?, ?) 
                ON DUPLICATE KEY UPDATE target_value = VALUES(target_value), set_by_user_id = VALUES(set_by_user_id)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("isii", $user_id, $target_date, $new_target, $admin_id);
        
        if ($stmt->execute()) {
            $_SESSION['message'] = "Target updated successfully for the selected date!";
            $_SESSION['message_type'] = 'success';
        } else {
            $_SESSION['message'] = "Error updating temporary target.";
            $_SESSION['message_type'] = 'error';
        }
        $stmt->close();
    } else {
        $_SESSION['message'] = "Target cannot be negative.";
        $_SESSION['message_type'] = 'error';
    }

    // Page par redirect karein taaki state (chuni hui date aur user) bani rahe
    header("Location: manage_daily_targets.php?target_date=" . urlencode($target_date) . "&user_id=" . urlencode($user_id));
    exit();
}

// --- DATA FETCHING ---
// Dropdown ke liye sabhi users ko fetch karein
$all_users_result = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
$all_users = $all_users_result->fetch_all(MYSQLI_ASSOC);

// Agar user chuna gaya hai, to uska target data fetch karein
$user_target_data = null;
if ($selected_user_id) {
    $sql = "SELECT u.name, u.daily_target as default_target, tt.target_value 
            FROM users u 
            LEFT JOIN temporary_targets tt ON u.id = tt.user_id AND tt.target_date = ?
            WHERE u.id = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $selected_date, $selected_user_id);
    $stmt->execute();
    $user_target_data = $stmt->get_result()->fetch_assoc();
    $stmt->close();
}

// Session se message prapt karein
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

require_once 'header.php';
?>

<!-- Custom CSS for this page only -->
<style>
    .target-card {
        transition: all 0.3s ease-in-out;
        border-radius: .35rem;
    }
    .target-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
    }
    .form-control-plaintext.bg-light {
        border-radius: 0.25rem;
        padding-left: .75rem;
    }
</style>

<div class="container-fluid">
    <h1 class="mt-4">Manage Daily Targets</h1>
    <ol class="breadcrumb mb-4">
        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
        <li class="breadcrumb-item active">Manage Targets</li>
    </ol>

    <?php if (!empty($message)): ?>
        <div class="alert <?php echo ($message_type == 'success') ? 'alert-success' : 'alert-danger'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <!-- Step 1: Selection Form -->
    <div class="card mb-4 shadow-sm target-card">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-filter mr-2"></i>Select Employee and Date</h5>
        </div>
        <div class="card-body">
            <form action="manage_daily_targets.php" method="GET" class="form-row align-items-end">
                <div class="form-group col-md-4">
                    <label for="target_date" class="font-weight-bold">Select Date:</label>
                    <input type="date" name="target_date" id="target_date" class="form-control" value="<?php echo htmlspecialchars($selected_date); ?>">
                </div>
                <div class="form-group col-md-6">
                    <label for="user_id" class="font-weight-bold">Select Employee:</label>
                    <select name="user_id" id="user_id" class="form-control">
                        <option value="">-- Select an Employee --</option>
                        <?php foreach ($all_users as $user): ?>
                            <option value="<?php echo $user['id']; ?>" <?php if ($selected_user_id == $user['id']) echo 'selected'; ?>>
                                <?php echo htmlspecialchars($user['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group col-md-2">
                    <button type="submit" class="btn btn-primary btn-block">View Target</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Step 2: Update Form (agar user chuna gaya hai to dikhayein) -->
    <?php if ($selected_user_id && $user_target_data): ?>
    <div class="card shadow-sm target-card">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-bullseye mr-2"></i>Update Target for <?php echo htmlspecialchars($user_target_data['name']); ?> on <?php echo date("d M, Y", strtotime($selected_date)); ?></h5>
        </div>
        <div class="card-body">
            <form method="POST" action="manage_daily_targets.php">
                <input type="hidden" name="user_id" value="<?php echo $selected_user_id; ?>">
                <input type="hidden" name="target_date" value="<?php echo $selected_date; ?>">
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Default Target</label>
                            <input type="text" class="form-control-plaintext bg-light" value="<?php echo htmlspecialchars($user_target_data['default_target']); ?> tasks/day" readonly>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="new_target">Set Target for Selected Date</label>
                            <input type="number" name="new_target" id="new_target" class="form-control" 
                                   value="<?php echo htmlspecialchars($user_target_data['target_value'] ?? $user_target_data['default_target']); ?>" 
                                   min="0" required>
                        </div>
                    </div>
                    <div class="col-md-4 align-self-end">
                        <div class="form-group">
                             <button type="submit" name="update_target" class="btn btn-success btn-block">
                                <i class="fas fa-save mr-2"></i>Update Target for this Date
                            </button>
                        </div>
                    </div>
                </div>
                 <p class="text-muted small mt-2">Note: This will only change the target for the selected date (<?php echo date("d M, Y", strtotime($selected_date)); ?>). The default target will remain unchanged.</p>
            </form>
        </div>
    </div>
    <?php elseif (isset($_GET['user_id']) && !empty($_GET['user_id'])): ?>
        <div class="alert alert-warning">The selected employee could not be found. Please select a valid employee.</div>
    <?php endif; ?>
</div>

<?php
$conn->close();
require_once 'footer.php';
?>

