<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

require_once("../config.php");

header('Content-Type: text/plain');
header('Allow-Control-Allow-Origin: *');
$json_data = file_get_contents("php://input");
$data = json_decode($json_data, true);
// echo json_encode($data);
// exit();
// echo "Config";
if(isset($data['code'])){
    $code = mysqli_real_escape_string($db, $data['code']);
    // $d = mysqli_fetch_assoc(mysqli_query($db, "SELECT t1.employee_id, t1.name, t1.email, t1.phone, t1.leader, t1.dob, t1.joining_date, t1.blood_group, t1.image, t2.department_name, t3.designation_name, t4.name as leader_name
    //     FROM users t1
    //     INNER JOIN departments t2 ON t2.id=t1.department
    //     INNER JOIN designations t3 ON t3.id=t1.designation
    //     INNER JOIN users t4 ON t4.employee_id=t1.leader
    //     WHERE t1.hash_email='$code' "));

    $d = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM
    (
        SELECT
            t1.*,
            t2.name AS leader_name,
            t3.department_name,
            t4.designation_name
        FROM (
            SELECT 
                p1.*,
                (CASE
                WHEN COALESCE(p2.promote_to,'')<>'' THEN p2.promote_to
                ELSE p1.designation
                END) AS new_designation
            FROM users p1
            LEFT JOIN (
                SELECT
                    *
                FROM (
                    SELECT 
                        id,
                        employee_id, 
                        promote_to, 
                        applicable_from, 
                        (CASE 
                        WHEN COALESCE(applicable_to,'')='' THEN DATE_FORMAT(CURRENT_DATE, '%Y-%m')
                        ELSE applicable_to
                        END) as applicable_to 
                    FROM promotions
                ) final_promotions
                WHERE (DATE_FORMAT(CURRENT_DATE, '%Y-%m') BETWEEN applicable_from AND applicable_to)
            ) p2 ON p1.employee_id=p2.employee_id
        ) t1
        LEFT JOIN users AS t2 ON t1.leader = t2.employee_id
        LEFT JOIN departments AS t3 ON t3.id = t1.department
        LEFT JOIN designations AS t4 ON t4.id=t1.new_designation
    ) join_table
    WHERE hash_email='$code' "));

    $d['joining_date'] = !empty($d['joining_date'])?date('d M Y', strtotime($d['joining_date'])):'Not Available';
    $d['dob'] = !empty($d['dob'])?date('d M Y', strtotime($d['dob'])):'Not Available';
    $d['image'] = "https://cdn.nishtyainfotech.com/content/employee/images/".(!empty($d['image'])?$d['image']:'avatar.png');

    echo json_encode($d);
}



?>