<?php
require_once('config.php');

$site_cd    = $_REQUEST['site_cd'] ?? '';
$date       = $_REQUEST['date'] ?? '';
$screenname = $_REQUEST['screenname'] ?? 'dailyLinenRoutine';
$LOGINID    = $_REQUEST['LOGINID'] ?? '';
$all_dept   = filter_var($_GET['all_dept'], FILTER_VALIDATE_BOOLEAN);

$where_dept_mst_linen_porter = "";

if (!$all_dept && !empty($LOGINID)) {
   
    $where_dept_mst_linen_porter = " AND d.dept_mst_linen_porter =  '".$LOGINID."' ";
}



try {
    if ($site_cd === '' || $date === '') {
        throw new Exception("Missing required parameters: site_cd or date");
    }

    $screen = strtolower(trim($screenname));
    $json   = [];

    // =========================================================
    // 1) DailyLinenRoutine  (Department summary)
    // =========================================================
    if ($screen === 'dailylinenroutine') {
	

        $sql = "
            SELECT 
                d.dept_mst_dept_cod,
                d.dept_mst_description,
				d.dept_mst_linen_porter,
				

                COUNT(p.RowID) AS total_lines,

                l.lri_mst_lri_no,
				l.lri_mst_lri_date,
				l.lri_mst_status,
				l.lri_mst_RowID,
				l.lri_mst_create_by,
				l.audit_date,
				
				det.lri_det_sign_by,
				det.lri_det_sign_by_id,
				det.lri_det_sign_by_contact,
				
				sts.lri_sts_typ_cd,
				sts.lri_sts_desc,

                status_color = CASE 
                                  WHEN l.lri_mst_status = 'OPN' THEN '#12b728'
                                  WHEN l.lri_mst_status = 'CNT' THEN '#F79009'
                                  WHEN l.lri_mst_status = 'ISU' THEN '#D32F2F'
								  WHEN l.lri_mst_status = 'CLO' THEN '#D32F2F'
                                  ELSE '#D0D5DD'
                               END,

                done_count = CASE 
                                WHEN l.lri_mst_RowID IS NULL THEN 0
                                ELSE ISNULL(sc.done_count, 0)
                             END,

                short_count = CASE
									WHEN l.lri_mst_RowID IS NULL THEN 0
									ELSE (COUNT(p.RowID) - ISNULL(sc.short_count,0))
								 END,

                progress_text = CONCAT(
                    CASE 
                        WHEN l.lri_mst_RowID IS NULL THEN 0
                        ELSE ISNULL(sc.done_count, 0)
                    END,
                    '/',
                    COUNT(p.RowID)
                ),
				progress = CONCAT(
									CASE 
										WHEN l.lri_mst_RowID IS NULL THEN 0
										ELSE ISNULL(sc.short_count,0)
									END,
									'/',
									COUNT(p.RowID)
								),

				-- ✅ partial issued count (issue1+issue2 not null) BUT if status ISU -> force 0
				partial_issued_count = CASE
											WHEN l.lri_mst_RowID IS NULL THEN 0
											WHEN l.lri_mst_status = 'ISU' THEN 0
											WHEN l.lri_mst_status = 'CLO' THEN 0
											ELSE ISNULL(sc.partial_issued_count,0)
										END,
										
										
				-- signature info
				signature_done_count = CASE
											WHEN l.lri_mst_RowID IS NULL THEN 0
											WHEN ISNULL(sig.signature_count, 0) > 0 THEN 1
											ELSE 0
									   END,

				signature_not_done_count = CASE
												WHEN l.lri_mst_RowID IS NULL THEN 0
												WHEN ISNULL(sig.signature_count, 0) > 0 THEN 0
												ELSE 1
										   END,

				signature_status = CASE
										WHEN l.lri_mst_RowID IS NULL THEN 'NO RECORD'
										WHEN ISNULL(sig.signature_count, 0) > 0 THEN 'SIGNED'
										ELSE 'NOT SIGNED'
								   END,
				
			 sort_order = CASE
				WHEN l.lri_mst_RowID IS NULL THEN 0          -- not entered (top)
				WHEN l.lri_mst_status = 'OPN' THEN 1         -- open (top)
				WHEN l.lri_mst_status = 'ISU' THEN 2
				WHEN l.lri_mst_status = 'CNT' THEN 3        
				WHEN l.lri_mst_status = 'CLO' THEN 4         -- Close (bottom)
				ELSE 5
			 END

            FROM dept_mst d 

            JOIN dept_par p WITH (NOLOCK)
              ON d.site_cd = p.site_cd
             AND d.RowID   = p.mst_RowID

            OUTER APPLY (
                SELECT TOP 1 
                    lm.RowID AS lri_mst_RowID,
                    lm.lri_mst_lri_no,
                    lm.lri_mst_lri_date,
                    lm.lri_mst_status,
					lm.lri_mst_create_by,
					lm.audit_date
                FROM lri_mst lm WITH (NOLOCK)
                WHERE lm.site_cd = ?
                  AND lm.lri_mst_department = d.dept_mst_dept_cod
                  AND lm.lri_mst_lri_date >= ?
                  AND lm.lri_mst_lri_date < DATEADD(DAY, 1, ?)
                ORDER BY lm.lri_mst_lri_date DESC
            ) l

			
			LEFT JOIN lri_sts sts WITH (NOLOCK)
			ON sts.site_cd = ?
			AND sts.lri_sts_status = l.lri_mst_status 
			
			LEFT JOIN lri_det det WITH (NOLOCK)
			ON det.site_cd = ?
			AND det.mst_RowID = l.lri_mst_RowID
			
			
			OUTER APPLY (
				SELECT 
					signature_count = COUNT(1)
				FROM lri_ref ref WITH (NOLOCK)
				WHERE ref.site_cd = ?
				  AND ref.mst_RowID = l.lri_mst_RowID
			) sig
			 
            OUTER APPLY (
                SELECT 
                    done_count = COUNT(CASE WHEN ls.lri_ls1_bal_qty IS NOT NULL THEN 1 END),
                    short_count =
						SUM(CASE
							  WHEN ls.lri_ls1_par_qty IS NOT NULL
							   AND ls.lri_ls1_bal_qty IS NOT NULL
							   AND (
									ISNULL(ls.lri_ls1_par_qty,0)
								  - ISNULL(ls.lri_ls1_bal_qty,0)
								  - ISNULL(ls.lri_ls1_issue1_qty,0)
								  - ISNULL(ls.lri_ls1_issue2_qty,0)
								   ) <= 0
							  THEN 1
							  ELSE 0
							END),					
					partial_issued_count = SUM(CASE WHEN ls.lri_ls1_issue1_qty IS NOT NULL OR ls.lri_ls1_issue2_qty IS NOT NULL THEN 1 ELSE 0 END)

                FROM lri_ls1 ls WITH (NOLOCK)
                WHERE ls.site_cd = ?
                  AND ls.mst_RowID = l.lri_mst_RowID
            ) sc

            WHERE d.dept_mst_disable_flag = '0'
              AND d.site_cd = ?
			  ".$where_dept_mst_linen_porter."

            GROUP BY 
                d.dept_mst_dept_cod,
				d.dept_mst_description,
				d.dept_mst_linen_porter,
				l.lri_mst_RowID,
				l.lri_mst_lri_no,
				l.lri_mst_lri_date,
				l.lri_mst_status,
				l.lri_mst_create_by,
				l.audit_date,
				det.lri_det_sign_by,
				det.lri_det_sign_by_id,
				det.lri_det_sign_by_contact,
				sts.lri_sts_typ_cd,
				sts.lri_sts_desc,
				sc.done_count,
				sc.short_count,
				sc.partial_issued_count,
				sig.signature_count

            ORDER BY  sort_order ASC, d.dept_mst_dept_cod
        ";

        $params = [$site_cd, $date, $date, $site_cd, $site_cd, $site_cd, $site_cd,$site_cd, $site_cd];

        $stmt = sqlsrv_query($conn, $sql, $params);
        if ($stmt === false) {
            throw new Exception("SQL error: " . print_r(sqlsrv_errors(), true));
        }

        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            if (isset($row['lri_mst_lri_date']) && $row['lri_mst_lri_date'] instanceof DateTime) {
                $row['lri_mst_lri_date'] = $row['lri_mst_lri_date']->format('Y-m-d H:i:s');
            }
            $json[] = $row;
        }

        sqlsrv_free_stmt($stmt);
    }

    // =========================================================
    // 2) DailylinenIssue  (Only linen + date)
    // =========================================================
    elseif ($screen === 'dailylinenissue') {

       $sql = "
				SELECT 
					d.dept_mst_dept_cod,
					d.dept_mst_description,

					COUNT(p.RowID) AS total_lines,

					l.lri_mst_lri_no,
					l.lri_mst_lri_date,
					l.lri_mst_status,
					l.lri_mst_RowID,
					l.audit_date,

					sts.lri_sts_typ_cd,
					sts.lri_sts_desc,

					det.lri_det_sign_by,
					det.lri_det_sign_by_id,
					det.lri_det_sign_by_contact,

					status_color = CASE 
									  WHEN l.lri_mst_status = 'OPN' THEN '#12b728'
									  WHEN l.lri_mst_status = 'CNT' THEN '#F79009'
									  WHEN l.lri_mst_status = 'ISU' THEN '#D32F2F'
									  ELSE '#D0D5DD'
								   END,

					done_count = CASE 
									WHEN l.lri_mst_RowID IS NULL THEN 0
									ELSE ISNULL(sc.short_count, 0)
								  END,

					short_count = CASE
									WHEN l.lri_mst_RowID IS NULL THEN 0
									ELSE (COUNT(p.RowID) - ISNULL(sc.short_count,0))
								 END,

					progress_text = CONCAT(
									CASE 
										WHEN l.lri_mst_RowID IS NULL THEN 0
										ELSE ISNULL(sc.short_count,0)
									END,
									'/',
									COUNT(p.RowID)
								),
					 -- ✅ partial issued count (issue1+issue2 not null) BUT if status ISU -> force 0
					partial_issued_count = CASE
											  WHEN l.lri_mst_RowID IS NULL THEN 0
											  WHEN l.lri_mst_status = 'ISU' THEN 0
											  ELSE ISNULL(sc.partial_issued_count,0)
										   END,

					-- ✅ status text
					issue_status = CASE
									  WHEN l.lri_mst_RowID IS NULL THEN 'NOT_ENTERED'
									  WHEN l.lri_mst_status = 'ISU' THEN 'ISSUED'
									  WHEN ISNULL(sc.partial_issued_count,0) > 0 THEN 'PARTIAL_ISSUED'
									  ELSE 'NOT_ISSUED'
								   END

				FROM dept_mst d 
				JOIN dept_par p WITH (NOLOCK)
				  ON d.site_cd = p.site_cd
				 AND d.RowID   = p.mst_RowID

				OUTER APPLY (
					SELECT TOP 1 
						lm.RowID AS lri_mst_RowID,
						lm.lri_mst_lri_no,
						lm.lri_mst_lri_date,
						lm.lri_mst_status,
						lm.audit_date
					FROM lri_mst lm WITH (NOLOCK)
					WHERE lm.site_cd = ?
					  AND lm.lri_mst_department = d.dept_mst_dept_cod
					  AND lm.lri_mst_lri_date >= ?
					  AND lm.lri_mst_lri_date < DATEADD(DAY, 1, ?)
					ORDER BY lm.lri_mst_lri_date DESC
				) l

				LEFT JOIN lri_det det WITH (NOLOCK)
				  ON det.site_cd = ?
				 AND det.mst_RowID = l.lri_mst_RowID

				LEFT JOIN lri_sts sts WITH (NOLOCK)
				  ON sts.site_cd = ?
				 AND sts.lri_sts_status = l.lri_mst_status 

				OUTER APPLY (
					SELECT 
						short_count =
						SUM(CASE
							  WHEN ls.lri_ls1_par_qty IS NOT NULL
							   AND ls.lri_ls1_bal_qty IS NOT NULL
							   AND (
									ISNULL(ls.lri_ls1_par_qty,0)
								  - ISNULL(ls.lri_ls1_bal_qty,0)
								  - ISNULL(ls.lri_ls1_issue1_qty,0)
								  - ISNULL(ls.lri_ls1_issue2_qty,0)
								   ) <= 0
							  THEN 1
							  ELSE 0
							END),
							
							-- ✅ new: partial issued lines (issue1 not null AND issue2 not null)
							partial_issued_count =
								SUM(CASE
									  WHEN ls.lri_ls1_issue1_qty IS NOT NULL
									   OR ls.lri_ls1_issue2_qty IS NOT NULL
									  THEN 1
									  ELSE 0
									END)
									
					FROM lri_ls1 ls WITH (NOLOCK)
					WHERE ls.site_cd = ?
					  AND ls.mst_RowID = l.lri_mst_RowID
				) sc

				WHERE d.dept_mst_disable_flag = '0'
				  AND d.site_cd = ?
				  AND l.lri_mst_lri_date >= ?
				  AND l.lri_mst_lri_date < DATEADD(DAY, 1, ?)
				  AND l.lri_mst_status IN ('CNT','ISU')

				GROUP BY 
					d.dept_mst_dept_cod,
					d.dept_mst_description,
					l.lri_mst_RowID,
					l.lri_mst_lri_no,
					l.lri_mst_lri_date,
					l.lri_mst_status,
					l.audit_date,
					sts.lri_sts_typ_cd,
					sts.lri_sts_desc,
					det.lri_det_sign_by,
					det.lri_det_sign_by_id,
					det.lri_det_sign_by_contact,
					sc.short_count,
					sc.partial_issued_count

				ORDER BY d.dept_mst_dept_cod
			";

			$params = [
				$site_cd, $date, $date,   // OUTER APPLY l
				$site_cd,                 // lri_det
				$site_cd,                 // lri_sts
				$site_cd,                 // OUTER APPLY sc
				$site_cd,                 // WHERE d.site_cd
				$date, $date              // WHERE date range
			];

			$stmt = sqlsrv_query($conn, $sql, $params);
			if ($stmt === false) {
				throw new Exception("SQL error: " . print_r(sqlsrv_errors(), true));
			}

        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            if (isset($row['lri_mst_lri_date']) && $row['lri_mst_lri_date'] instanceof DateTime) {
                $row['lri_mst_lri_date'] = $row['lri_mst_lri_date']->format('Y-m-d H:i:s');
            }
            $json[] = $row;
        }

        sqlsrv_free_stmt($stmt);
    }
    else {
        throw new Exception("Invalid screenname. Use DailyLinenRoutine or DailylinenIssue");
    }

    sqlsrv_close($conn);

    // ✅ SAME JSON FORMAT FOR BOTH
    echo json_encode([
        'status' => 'SUCCESS',
        'data'   => $json
    ]);

} catch (Exception $e) {

    if (isset($conn)) @sqlsrv_close($conn);

    echo json_encode([
        'status'  => 'ERROR',
        'message' => $e->getMessage(),
        'data'    => []
    ]);
    exit();
}
?>