I did it in a totally different way.
I received the required by date, created a date range of 2 months, and then removed all Saturdays and Sundays PLUS already booked days from the array. And then I reverse sort, and pick the first required amount of days.
function _createDateRangeArray($strDateFrom,$strDateTo) {
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
public function confirm($id = null) {
if($this->request->is('post')) {
$this->TenderDocument->create();
$data = array(
'TenderDocument' => array(
'id' => $id,
'book_dates' => implode(',',$this->request->data['TenderDocument']['book_days'])
)
);
if($this->TenderDocument->save($data)) {
$this->_sendTenderDocument($id);
$this->Session->setFlash('Tender document request saved.','default',array('class'=>'notification'));
$this->redirect(array('action'=>'add'));
} else {
$this->Session->setFlash('There was an error saving your deadline. Please retry.','default',array('class'=>'error'));
}
}
$this->TenderDocument->id = $id;
if (!$this->TenderDocument->exists()) {
throw new NotFoundException(__('Invalid tender document'));
}
$tenderDocument = $this->TenderDocument->read(null,$id);
$deadline = $tenderDocument['TenderDocument']['required_date']; // Deadline date as entered on form
$deadline = $start = date('Y-m-d',strtotime('-1 day',strtotime($deadline))); // adjusted deadline
$start = date('Y-m-d',strtotime('-3 months',strtotime($deadline))); // adjusted start
$period = $this->_createDateRangeArray($start,$deadline);
$TenderDocuments = $this->TenderDocument->find('list',
array(
'fields' => array('TenderDocument.book_dates')
)
);
$dates = array();
foreach($TenderDocuments as $TenderDocument) {
$doc_dates = explode(',',$TenderDocument);
foreach($doc_dates as $doc_date) {
$dates[] = $doc_date;
}
}
foreach($period as $key=>$value) {
if(date('l',strtotime($value)) == 'Saturday' || date('l',strtotime($value)) == 'Sunday' || in_array($value,$dates)) {
unset($period[$key]);
}
}
rsort($period);
for($k = 0; $k <= $tenderDocument['ContractForm']['time']; $k++) {
$book_days[] = $period[$k];
}
$this->set('TenderDocument',$this->TenderDocument->read(null,$id));
$this->set('book_days',$book_days);
}
If there is any way I can streamline this code and make it faster, feel free to comment.